动态生成的ListView不会根据其模型进行填充

时间:2017-05-19 22:45:07

标签: qt user-interface dynamic combobox qml

我正在通过向Qt.createQmlObject发送字符串来手动创建组合框,如下所示:

var newQML = "ComboBox {\n";
newQML += "  model: ListModel {\n"
newQML += "    ListElement {\n"
newQML += "      name: \"One\"\n"
newQML += "    }\n"
newQML += "  }\n"
newQML += "}\n"

var cBox = Qt.createQmlObject(newQML)

但是,组合框不会填充其ListModel中的条目(它只是保持为空。)我还尝试在组件中创建一个ListModel,将其实例化,给它一个id,然后尝试引用该id在我的代码中如此:

var newQML = "ComboBox {\n";
newQML += "  model: sampleModel\n"
newQML += "}\n"

var cBox = Qt.createQmlObject(newQML)

然而,这也不起作用。请让我知道在QML中动态实例化和填充ComboBox的正确方法。

1 个答案:

答案 0 :(得分:0)

首先,import语句应该包含在传递给Qt.createQmlObject的字符串中。由于您使用的是ListModelComboBox,因此您应该在QtQuick中导入QtQuick.ControlsnewQML

var newQML = "import QtQuick 2.0; \n";
newQML += "import QtQuick.Controls 2.0\n";
newQML += "ComboBox {\n";
newQML += "  model: ListModel {\n"
newQML += "    ListElement {\n"
newQML += "      name: \"One\"\n"
newQML += "    }\n"
newQML += "  }\n"
newQML += "}\n"

接下来,您需要将父项传递给Qt.createQmlObject以指定绘制组合框的位置。例如,如果您将组合框放在mainItem中,那么将newQMLmainItem传递给Qt.createQmlObject

Item {
    id: mainItem
    width: 200; height: 200

    Button {
        anchors.centerIn: parent
        onClicked: {
            var newQML = "import QtQuick 2.0; \n";
            newQML += "import QtQuick.Controls 2.0\n";
            //...

            var cBox = Qt.createQmlObject(newQML, mainItem);
        }
    }
}

但是,如果您使用QtQuick.Controls 1.x中的组合框,则上述方法无效,程序会为您提供一个空的组合框(在Qt 5.8 MSVC 2015中测试)。一个简单的解决方法是在创建对象后分配模型:

var newQML = "import QtQuick 2.7; \n";
newQML += "import QtQuick.Controls 1.4\n";
newQML += "ComboBox {\n";
newQML += "}\n"

var cBox = Qt.createQmlObject(newQML, mainItem)
cBox.model = sampleModel;

但我认为最好使用QtQuick.Controls 2Qt.createComponent