Skip to content

Examples

mkottman edited this page Aug 15, 2011 · 4 revisions
Clone this wiki locally

The basic application

require 'qtcore'
require 'qtgui'

app = QApplication.new(select('#',...) + 1, {'lua', ...})
-- YOUR CODE GOES HERE
app.exec()

In later examples, this boilerplate code will not be shown again.

Handling events

w = QWidget.new()
function w:closeEvent(e)
    print('Closing!')
end
w:show()

TableView, item model and custom delegates

local model = QStandardItemModel.new(4, 2)
local tableView = QTableView.new()
tableView:setModel(model)

local delegate = QItemDelegate.new()

-- override the virtual functions needed for QItemDelegate to work
-- you have to create them directly on the instance, not in a class

function delegate:createEditor(parent, option, index)
    local editor = QSpinBox.new(parent)
    editor:setMinimum(0)
    editor:setMaximum(100)
    return editor
end

function delegate:setEditorData(editor, index)
    print('setEditorData', editor.__type, index.__type)
    local value = index:model():data(index, Qt.ItemDataRole.EditRole):toInt()
    -- QObject derivates are automatically cast to the correct type,
    -- in this case, QSpinBox
    editor:setValue(value)
end

function delegate:setModelData(editor, model, index)
    print('setModelData', editor.__type, model.__type, index.__type)
    editor:interpretText()
    local value = editor:value()
    model:setData(index, value, Qt.ItemDataRole.EditRole)
end

function delegate:updateEditorGeometry(editor, option, index)
    print('updateEditorGeometry', editor.__type, option.__type, index.__type)
    editor:setGeometry(option.rect)
end

tableView:setItemDelegate(delegate)
tableView:horizontalHeader():setStretchLastSection(true)

for row=0,3 do
    for column=0,1 do
        local index = model:index(row, column)
        model:setData(index, (row+1)*(column+1))
    end
end

tableView:setWindowTitle("Spin Box Delegate")
tableView:show()

Animation

local W=QWidget.new()
local button=QPushButton.new(W)
local animation=QPropertyAnimation.new(button, "geometry")
animation:setDuration(2000)
animation:setStartValue(QRect.new(0,0,100,30))
animation:setEndValue(QRect.new(250,250,100,30))
button:__addmethod("start()", function()
    animation:start()
end)
button:connect("2clicked()", button, "1start()")

W:resize(350,280)
W:show()

SQL

require 'qtcore'
require 'qtsql'

-- to search for Qt plugins also in current directory
QCoreApplication.addLibraryPath(".")

local db = QSqlDatabase.addDatabase("QSQLITE", "conn1")
db:setDatabaseName("numbers.db")
if not db:open() then
    local err = db:lastError()
    error(err:text():toLocal8Bit())
end
db:exec("CREATE TABLE IF NOT EXISTS tab (n INT)")

local q = QSqlQuery.new_local(db)
q:prepare("INSERT INTO tab VALUES (:n)")
q:bindValue("n", 123)
q:exec()

local q2 = QSqlQuery.new_local(db)
q2:exec("SELECT * FROM tab")
while q2:next() do
    local v = q2:value(0)
    print(v:type(), v:toInt())
end

Fun with WebKit

require'qtwebkit'

webView = QWebView.new_local()
webView:setUrl(QUrl.new_local("http://www.lua.org"))
webView:show()

-- report every link through a signal
webView:page():setLinkDelegationPolicy('DelegateAllLinks')
webView:__addmethod('joke(QUrl)', function(self, url)
    url = url:toString():toUtf8()
    self:setHtml(string.format([=[
<h1>404 - Not Found</h1>Sorry, this is just a joke, you wanted to go to <a href="%s">%s</a>.
]=], url, url))
    webView:page():setLinkDelegationPolicy('DontDelegateLinks')
end)
webView:connect('2linkClicked(QUrl)', webView, '1joke(QUrl)')

A simple-but-useful Markdown viewer using Webkit

require 'qtcore'
require 'qtgui'
require 'qtwebkit'

-- requires the markdown.lua module: http://www.frykholm.se/files/markdown.lua
require 'markdown'

-- read the file provided as the first argument
file = assert(io.open(arg[1]))
source = file:read('*a')

app = QApplication(1+select('#', ...), {'MDView', ...})

view = QWebView()
-- convert the Markdown source to HTML and show it
view:setHtml(markdown(source))
view:show()

app.exec()
Something went wrong with that request. Please try again.