[PySide] What can be returned from a slot?
Aaron Richiger
a.richi at bluewin.ch
Sun Jan 13 14:32:10 CET 2013
Hello Yosef!
I think, this question is related to an earlier one from me... Anatoly
then told me the truth about lifetimes of QObjects that are created in
methods without any parent reference. They won't survive such a method
call as you try to do. By giving your model a parent reference that
survives the method call, the model will be available as well after the
return statement. The following code also shows, that the "QVariant"
trick is not necessary, but setting the result type to QObject is
enough. I hope this helps...
Aaron
################ Python code ##################
import sys
from PySide import QtCore, QtGui, QtDeclarative
class TargetListModel(QtCore.QAbstractListModel):
def __init__(self, targets, parent):
super(TargetListModel, self).__init__(parent)
self._targets = targets
self.setRoleNames({0: 'posx', 1: 'posy'})
@QtCore.Slot(result=int)
def rowCount(self, parent=QtCore.QModelIndex()):
return len(self._targets)
class Console(QtCore.QObject):
@QtCore.Slot(result=QtCore.QObject)
def get_model(self):
return TargetListModel("asdf", self)
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
view = QtDeclarative.QDeclarativeView()
con = Console()
context = view.rootContext()
context.setContextProperty("con", con)
view.setSource(QtCore.QUrl('view.qml'))
view.show()
sys.exit(app.exec_())
############### QML code in view.qml #########################
import Qt 4.7
Rectangle {
id: page
width: 500; height: 200
color: "lightgray"
Text {
id: helloText
text: "Hello world!"
anchors.horizontalCenter: page.horizontalCenter
y: 30
font.pointSize: 24; font.bold: true
}
Rectangle {
id: button
width: 150; height: 40
color: "darkgray"
anchors.horizontalCenter: page.horizontalCenter
y: 120
MouseArea {
id: buttonMouseArea
objectName: "buttonMouseArea"
anchors.fill: parent
onClicked: {
helloText.rotation = con.get_model().rowCount()
}
}
Text {
id: buttonText
text: "Press me!"
anchors.horizontalCenter: button.horizontalCenter
anchors.verticalCenter: button.verticalCenter
font.pointSize: 16;
}
}
}
More information about the PySide
mailing list