我想要实现的行为是通过从下拉框中选择,您将看到不同的QML组件。因此,如果用户选择“Apple”,则将查看Apple组件,否则将查看“香蕉”组件。到目前为止,我的方法是将ListView与Loader委托一起使用,如下所示,但是我的组件根本不显示。有没有更好的方法来实现我所追求的行为
view.qml
import QtQuick 2.0
import QtQuick.Layouts 1.12
import QtQuick.Controls 2.12
import QtQuick.Window 2.12
ApplicationWindow {
id: page
width: 400
height: 400
visible: true
ColumnLayout {
ListModel {
id: nullmodel
}
ComboBox {
id: selector
currentIndex: 1
model: ListModel {
id: cbItems
ListElement { text: "Apple"; }
ListElement { text: "Banana"; }
}
onCurrentIndexChanged: viewer.selected = cbItems.get(currentIndex).text
}
ListView {
model: nullmodel
id: viewer
property string selected: "Apple"
delegate: Loader {
sourceComponent: {
switch(selected)
{
case "Apple": {
console.log("Apples!")
return Apple
}
case "Banana": {
console.log("Bananas!")
return Banana
}
default:
console.log("Neither")
return Apple
}
}
}
}
}
}
Apple.qml
import QtQuick 2.0
Item {
Text {
text: "Hi, I'm an Apple"
}
}
香蕉
import QtQuick 2.0
Item {
Text {
text: "Hi, I'm a Banana"
}
}
如果有任何关联,我将使用PySide2来显示
main.py
import sys
from os.path import abspath, dirname, join
from PySide2.QtCore import QObject, Slot
from PySide2.QtGui import QGuiApplication
from PySide2.QtQml import QQmlApplicationEngine
if __name__ == '__main__':
app = QGuiApplication(sys.argv)
engine = QQmlApplicationEngine()
qmlFile = join(dirname(__file__), 'view.qml')
engine.load(abspath(qmlFile))
if not engine.rootObjects():
sys.exit(-1)
sys.exit(app.exec_())
考虑此代码:
为了实现你的目标,孤独就足够了。然而,你可以把它放在任何你想放的地方,例如
ListView
相关问题 更多 >
编程相关推荐