1 回答
TA贡献1725条经验 获得超7个赞
如果分析 QML 代码,只需要从 python 中创建一个模型(例如 QStandardItemModel),用 setContextProperty 将其导出到 QML 并在 ListView 中设置。
import sys
from PyQt5 import QtCore, QtGui, QtQuick
class QDrawer(QtQuick.QQuickView):
def __init__(self, parent=None):
super().__init__(parent)
self.setResizeMode(self.SizeRootObjectToView)
self.entry_model = QtGui.QStandardItemModel()
self.rootContext().setContextProperty("entry_model", self.entry_model)
self.setSource(QtCore.QUrl.fromLocalFile("main.qml"))
def addEntry(self, entry):
it = QtGui.QStandardItem(entry)
self.entry_model.appendRow(it)
def main():
app = QtGui.QGuiApplication(sys.argv)
w = QDrawer()
for i in range(10):
w.addEntry("entry-{}".format(i))
w.show()
sys.exit(app.exec_())
if __name__ == "__main__":
main()
main.qml
import QtQuick 2.12
import QtQuick.Controls 2.12
import QtQuick.Layouts 1.12
import QtQuick.Window 2.12
Rectangle {
id: window
width: 360
height: 520
color: "#00000000"
readonly property int dpi: Screen.pixelDensity * 25.4
function dp(x){ return (dpi < 120) ? x : x*(dpi/160); }
// Application Bar
Rectangle {
id: menuRect
anchors.top: parent.top
anchors.left: parent.left
anchors.right: parent.right
height: dp(48)
color: "#4cd964"
// Icon-Hamburger
Rectangle {
anchors.top: parent.top
anchors.bottom: parent.bottom
anchors.left: parent.left
width: dp(48)
color: "#4cd964"
Rectangle {
anchors.top: parent.top
anchors.topMargin: dp(16)
anchors.left: parent.left
anchors.leftMargin: dp(14)
width: dp(20)
height: dp(2)
}
Rectangle {
anchors.top: parent.top
anchors.topMargin: dp(23)
anchors.left: parent.left
anchors.leftMargin: dp(14)
width: dp(20)
height: dp(2)
}
Rectangle {
anchors.top: parent.top
anchors.topMargin: dp(30)
anchors.left: parent.left
anchors.leftMargin: dp(14)
width: dp(20)
height: dp(2)
}
MouseArea {
anchors.fill: parent
onClicked: {
nav.toggle()
}
}
}
}
Label{
id: label
anchors.top: menuRect.bottom
anchors.left: parent.left
anchors.right: parent.right
anchors.bottom: parent.bottom
horizontalAlignment: Text.AlignHCenter
verticalAlignment: Text.AlignVCenter
}
NavigationDrawer {
id: nav
width: window.width * .75
Rectangle {
anchors.fill: parent
color: "white"
ListView {
anchors.fill: parent
delegate: Item {
height: dp(48)
anchors.left: parent.left
anchors.right: parent.right
Rectangle {
anchors.fill: parent
anchors.margins: dp(5)
color: "whitesmoke"
Text {
text: model.display
anchors.fill: parent
font.pixelSize: dp(20)
renderType: Text.NativeRendering
horizontalAlignment: Text.AlignHCenter
verticalAlignment: Text.AlignVCenter
}
MouseArea {
anchors.fill: parent
onClicked: {
label.text = index + " : " + model.display
nav.hide()
}
}
}
}
model: entry_model
}
}
}
}
添加回答
举报