Created
December 29, 2020 22:51
-
-
Save dridk/926a6a068a0b10c6ee3d7f0a7adbeceb to your computer and use it in GitHub Desktop.
qml and python model integration with PySide2
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from PySide2.QtWidgets import * | |
from PySide2.QtCore import * | |
from PySide2.QtGui import * | |
from PySide2.QtQuick import QQuickView | |
import sys | |
import random | |
class PlayerModel(QAbstractListModel): | |
""" | |
Create a Qt model | |
""" | |
def __init__(self, parent=None): | |
super().__init__(parent) | |
self.players = [ | |
{"name": "Boby", "skill": "magie"}, | |
{"name": "Lara", "skill": "fight"}, | |
] | |
def rowCount(self, index=QModelIndex()): | |
""" override """ | |
return len(self.players) | |
def data(self, index: QModelIndex(), role: Qt.ItemDataRole): | |
""" override """ | |
if not index.isValid(): | |
return None | |
if role == Qt.DisplayRole: | |
return self.players[index.row()] | |
@Slot() | |
def add_item(self): | |
self.beginInsertRows(QModelIndex(), 0, 0) | |
self.players.insert( | |
0, {"name": "Boby {}".format(random.randint(0, 100)), "skill": "magie"} | |
) | |
self.endInsertRows() | |
if __name__ == "__main__": | |
qml = """ | |
import QtQuick 2.0 | |
Rectangle { | |
width: 800 | |
height: 600 | |
Text { | |
anchors.right : parent.right | |
text:"Click on me" | |
font.pixelSize:20 | |
MouseArea{ | |
anchors.fill : parent | |
onClicked: myModel.add_item() | |
} | |
} | |
Column { | |
anchors.fill:parent | |
Repeater { | |
model: myModel | |
Row { | |
Text { | |
text:display["name"] | |
font.pixelSize: 40 | |
color:"red" | |
} | |
Text { | |
text:display["skill"] | |
font.pixelSize: 40 | |
color:"blue" | |
} | |
} | |
} | |
} | |
} | |
""" | |
with open("test.qml", "w") as file: | |
file.write(qml) | |
app = QApplication(sys.argv) | |
model = PlayerModel() | |
view = QQuickView() | |
view.rootContext().setContextProperty("myModel", model) | |
view.setSource(QUrl.fromLocalFile("test.qml")) | |
view.show() | |
app.exec_() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you it was more helpful than original qt for python documentation