首页 > 解决方案 > QML ComboBox 中的 Python 列表

问题描述

QML 新手。试图将 python 列表设置为 QML ComboBox。我创建了一个小的使用示例。请注意,在实际程序中,python 列表不是硬编码的。

蟒蛇类:

class Test(QObject):
    def __init__(self,):
        super().__init__()

    @Slot(result=list)
    def getList(self):
        return ["one", "two", "three"]

主要.py:

def main():
    app = QApplication(sys.argv)
    engine = QQmlApplicationEngine()
    test = Test()

    engine.rootContext().setContextProperty("Test", test)
    engine.load(QUrl.fromLocalFile(os.path.join(os.path.dirname(__file__), 'main.qml')))
    if not engine.rootObjects():
        raise Exception("No qml objects were loaded!")
    return app.exec_()

if __name__ == '__main__':
    sys.exit(main())

QML 组件:

ComboBox {
        id: combo
        width: parent.width
        model: Test.getList() // no idea what to write here
        textRole: "fileName"

        onAccepted: {
            print(combo.currentText)
        }
    }

谢谢!

标签: pythonqmlpyside2

解决方案


推荐阅读