【发布时间】:2021-03-03 11:16:45
【问题描述】:
我一直在尝试制作 10 个不同的元素,例如按钮,我可以使用中继器来做到这一点,但我在为每个新元素设置文本时遇到了麻烦。
我正在从 Python 列表中获取我想要设置的文本,并通过QStringListModel 将它们发送到 qml。文本按照我的意愿从列表中获取到 qml,但不知何故,中继器集是所有元素的文本,作为 Python 给出的列表中的最后一个字符串。
稍后我将提供代码以获得额外的解释,但现在我想看看是否有人知道我该怎么做......(问题是代码在另一个设备中,我正在等待它) .基本上我想做的是,例如,我在 python a_list = {buttonName, buttonAge, buttonHeight} 中有一个列表,我想在 qml 中创建多个按钮作为列表的大小(在本例中为 3)并更改每个我在中继器中制作的按钮的文本作为列表中的字符串)。
这是 main.py
import sys
from PySide2.QtCore import QUrl
from PySide2.QtGui import QGuiApplication
from PySide2.QtQml import QQmlApplicationEngine
from foo import FooController
if __name__ == '__main__':
app = QGuiApplication(sys.argv)
engine = QQmlApplicationEngine()
fooController = FooController()
engine.rootContext().setContextProperty("fooController", fooController)
engine.load(QUrl.fromLocalFile('main.qml'))
if not engine.rootObjects():
sys.exit(-1)
sys.exit(app.exec_())
这是 foo.py
from PySide2.QtCore import QObject, Property, Slot
class x:
def __init__(self, name, age):
self.name = name
self.age = age
class FooController(QObject):
def __init__(self, parent=None):
QObject.__init__(self, parent)
self.__text = "Foo"
self.__name = s1.name
self.__age = s1.age
@Property(str)
def text(self):
return self.__name
@Slot()
def clickListener(self):
print(self.__name)
这是 foo.qml
import QtQuick 2.9
import QtQuick.Controls 2.2
Button {
text: fooController.text
onClicked: fooController.clickListener()
}
这是包含中继器的 qml 窗口
import QtQuick 2.0
import "../components"
//import QtQuick.Timeline 1.0
import QtQuick.Controls 2.15
import QtQuick 2.15
import QtQuick.Window 2.15
import QtGraphicalEffects 1.15
import QtQuick.Layouts 1.15
import "../main.py"
window{
width: 1500
height: 920
minimumWidth: 1100
minimumHeight: 650
visible: true
color: "#00000000"
id: mainWindow
title: qsTr("--")
Rectangle{
id: rectangle
anchors.fill: parent
anchors.rightMargin: 0
anchors.bottomMargin: 0
anchors.leftMargin: 0
anchors.topMargin: 0
radius: 10
color: "#4642b6"
Flickable {
id: flickable
contentHeight: gridLayoutBottom.height
anchors.left: parent.left
anchors.right: parent.right
anchors.top: parent.top
anchors.bottom: parent.bottom
anchors.topMargin: 96
anchors.rightMargin: 8
anchors.leftMargin: 8
anchors.bottomMargin: 8
clip: true
ListModel {
id: imageModel
ListElement { _id: "tile0" }
}
Repeater {
model: imageModel
delegate: CustomMenuType{
ListView{
model: s
delegate: Text {
text: model.display
font.family: "Segoe UI"
color: "#ffffff"
}
}
//text: ListView.delegate.Text.text
font.pointSize: 9
Layout.alignment: Qt.AlignHCenter | Qt.AlignVCenter
}
}
}
}
}
【问题讨论】: