我正在尝试将Qt-Android程序的界面从QWidgets重写为QML。我以前从未使用过它,所以错误很明显而且很愚蠢。
新界面基于ListView:
它看起来像:
public void UpdateClaimSts(string[] ids) {
// :id_0, :id_1, ..., :id_N
string bindVariables = string.Join(", ", ids
.Select((id, index) => ":id_" + index.ToString()));
string query = string.Format(
@"UPDATE MYTABLE
SET STATUS = 'X'
WHERE TABLEID IN ({0})", bindVariables);
// Do not forget to wrap IDisposable into "using"
using (OracleCommand dbCommand = ...) {
...
// Each item of the ids should be assigned to its bind variable
for (int i = 0; i < ids.Length; ++i)
dbCommand.Parameters.Add(":id_" + i.ToString(), OracleType.VarChar).Value = ids[i];
...
main()中的列表是通过以下方式填充的:
ListView
{
id: listView
x: 16
y: 146
width: 262
height: 282
model: myModel
delegate: Item
{
x: 5
width: 80
height: 40
Row
{
id: row1
spacing: 10
Text
{
width: 50
text:model.modelData.getPassword
font.bold: true
anchors.verticalCenter: parent.verticalCenter
}
ProgressBar
{
value: model.modelData.getDifficulty
}
}
}
}
DataObject:
QList<QObject*> dataList;
dataList.append(new DataObject("Item 1", 50));
dataList.append(new DataObject("Item 2", 60));
dataList.append(new DataObject("Item 3", 70));
dataList.append(new DataObject("Item 4", 80));
QGuiApplication app(argc, argv);
qmlRegisterType<BackEnd>("tk.asciigames.backend", 1, 0, "BackEnd");
QQmlApplicationEngine engine;
engine.rootContext()->setContextProperty("myModel", QVariant::fromValue(dataList));
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
return app.exec();
在运行QML时,实际上显示了4行(按预期),但没有数据。 日志出现此类错误:
class DataObject : public QObject
{
Q_OBJECT
Q_PROPERTY(QString password READ getPassword)
Q_PROPERTY(unsigned int difficulty READ getDifficulty)
public:
DataObject(QString _pass, unsigned int _difficulty)
{
difficulty = _difficulty;
password = _pass;
}
QString getPassword()
{
return password;
}
unsigned int getDifficulty()
{
return difficulty;
}
private:
unsigned int difficulty;
QString password;
};
这些错误对应于QML行:
qrc:/main.qml:118:26: Unable to assign [undefined] to QString
qrc:/main.qml:124:28: Unable to assign [undefined] to double
因此,看起来QML会获取数组,但无法从数组中获取数据。
有人可以帮我发现错误吗?
答案 0 :(得分:3)
声明Q_PROPERTY时,将定义一个名称和一个getter函数。 c ++使用getter函数获取属性的实际值,但是QML引擎不了解该属性;它只知道属性名称(在此示例中为password
)
Q_PROPERTY(QString password READ getPassword)
因此,在您的QML文件中,更改行
text:model.modelData.getPassword
value: model.modelData.getDifficulty
到
text:model.modelData.password
value: model.modelData.difficulty
你应该很好。
请注意,您还可以使用缩短的语法来访问属性
value: model.modelData.difficulty // OK
value: model.difficulty // OK
value: modelData.difficulty // OK
value: difficulty // Still OK
value: model.model.model.model.model.modelData.difficulty // OK, but don't do that
您可能还希望将Q_PROPERTY标记为“常量”,以消除警告QQmlExpression: Expression qrc:/main.qml:25:20 depends on non-NOTIFYable properties:
Q_PROPERTY(QString password READ getPassword CONSTANT)