当我尝试初始化ComboBox的模型时,会弹出奇怪的错误
test.pro
# Add more folders to ship with the application, here
folder_01.source = qml/androidTest
folder_01.target = qml
DEPLOYMENTFOLDERS = folder_01
#QMAKE_CXXFLAGS += -std=c++0x
CONFIG += c++11
QT += qml quick
# The .cpp file which was generated for your project. Feel free to hack it.
SOURCES += main.cpp
OTHER_FILES += \
qml/androidTest/main.qml
的main.cpp
#include <QtGui/QGuiApplication>
#include <QQuickView>
int main(int argc, char *argv[])
{
QGuiApplication app(argc, argv);
QQuickView view;
view.setSource(QUrl("/Users/Qt/program/experiment_apps_and_libs/test/qml/test/main.qml"));
view.show();
return app.exec();
}
main1.qml
import QtQuick 2.2
import QtQuick.Controls 1.1
Rectangle {
width: 100
height: 62
ListModel{
id: modelA
}
ComboBox{
model: modelA
}
Component.onCompleted: {
modelA.append({"source" : "hhhh"})
}
}
错误消息
file:/// C:/Qt/Qt5.2.0/5.2.0/mingw48_32/qml/QtQuick/Controls/ComboBox.qml:496:TypeError:无法读取未定义的属性'constructor'
我该如何解决此错误?
编辑1:
我没有制作内联模型,因为我想分离模型和ComboBox的构造。我的英文很难解释,这是一个简单的例子
TextCB
Column{
id: root
function appendUnitModel(units){
for(var i = 0; i != units.length; ++i){
unitModel.append({"unit": units[i]});
}
}
property alias inputText: input.text
SystemPalette{id: palette}
ListModel{
id: unitModel
}
Row{
spacing: 5
Text{
id: input
color: palette.highlight
height: root.height / 2
width: root.width * 0.6
focus: true
font.family: "Helvetica"
font.pixelSize: 16; font.bold: true
//Behavior on height{ NumberAnimation{duration: 500} }
MouseArea{
anchors.fill: parent
onClicked: {
showKeyBoard()
}
}
}
ComboBox{
id: unitSelector
model: unitModel
editable: true
height: input.height
width: root.width - input.width
}
}
}
main2.qml
TextCB{
id: inputAndClear
height: root.height * 0.2
width: root.width
Component.onCompleted: {
var units = ["meters", "decimeters", "centimeters",
"millimeters", "kilometers", "inches",
"feet", "yards", "miles", "nautical miles",
"cables"]
inputAndClear.appendUnitModel(units)
}
}
分离模型和ComboBox的构造,我可以更容易地重复使用它。
编辑2: 对于那些不使用QtCreator的人,这里是命令行
此命令在OSX下,您可能需要在不同操作系统下稍微调整一下(例如:将lldb更改为gdb)
答案 0 :(得分:2)
问题是你正试图设置&#34;来源&#34; ListElement
的{{1}}的属性,而不是&#39; text&#39;它的期望。如果您更改以下行,则分别为:
ListModel
为:
modelA.append({"source" : "hhhh"})
它会起作用。或者,您也可以将以下行添加到ComboBox以使您的自定义角色生效:
modelA.append({"text" : "hhhh"})
有关它的详细说明,请参阅ComboBox代码:
ComboBox {
model: modelA
textRole: "source"
}
您的代码中还有其他一些小问题,例如硬编码Windows的qml路径,如下所示。您可以更改为&#34; main.qml&#34;简单地说,或者使用资源系统。
// No text role set, check whether model has a suitable role
// If 'text' is found, or there's only one role, pick that.
我个人在本地更改为:
view.setSource(QUrl("/Users/Qt/program/experiment_apps_and_libs/test/qml/test/main.qml"));
此外,您似乎为此实验设置了不必要的qmake选项,如下所示:
view.setSource(QUrl("main.qml"));
和
CONFIG += c++11
对于后者,您无需明确指定QT += qml quick
。