Skip to content
mkottman edited this page Feb 10, 2011 · 4 revisions

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
Clone this wiki locally