Skip to content

Instantly share code, notes, and snippets.

@dridk
Created December 29, 2020 22:51
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save dridk/926a6a068a0b10c6ee3d7f0a7adbeceb to your computer and use it in GitHub Desktop.
Save dridk/926a6a068a0b10c6ee3d7f0a7adbeceb to your computer and use it in GitHub Desktop.
qml and python model integration with PySide2
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_()
@erdurano
Copy link

erdurano commented May 1, 2021

Thank you it was more helpful than original qt for python documentation

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment