我编写了一个模型以将其与 QML 一起使用并正确定义了所有属性:
class Model: public QObject {
Q_OBJECT
Q_PROPERTY(QString title READ title CONSTANT)
Q_PROPERTY(QString request READ request CONSTANT)
Q_PROPERTY(int first READ first WRITE setFirst NOTIFY firstChanged)
Q_PROPERTY(int second READ second WRITE setSecond NOTIFY secondChanged)
Q_PROPERTY(int minimumValue READ minimumValue CONSTANT)
Q_PROPERTY(int maximumValue READ maximumValue CONSTANT)
Q_PROPERTY(bool isRange READ isRange CONSTANT)
Q_PROPERTY(int result READ result WRITE setResult)
... setters / getters / signals ...
}
然后我为使用以前的模型创建 QML 对话框的对象编写了代码:
RangeInputDialog::Result RangeInputDialog::exec() const {
QQmlEngine engine;
QQmlComponent component(&engine);
component.loadUrl(QUrl("qrc:///ui-common/ui/RangeInputDialog.qml"));
if (!component.isReady()) {
qDebug() << "Could not load range input dialog";
qDebug() << component.errors();
return Result::Error;
}
QQmlContext context(&engine);
context.setContextProperty("rangeDialogModel", &m_model);
QScopedPointer<QObject> window(component.create(&context));
if (window.isNull()) {
qDebug() << "Could not instance range input dialog";
return Result::Error;
}
QEventLoop loop;
QObject::connect(window.data(), SIGNAL(closing(QQuickCloseEvent *)), &loop, SLOT(quit()));
if (window->setProperty("visible", true)) {
loop.exec();
} else {
qDebug() << "Could not show range input dialog";
return Result::Error;
}
return static_cast<Result>(m_model.result());
}
setContextProperty
将 Model 与 QML Dialog 绑定(bind),在创建组件后它会抛出一堆错误:
qrc:///ui-common/ui/RangeInputDialog.qml:23:9: Unable to assign [undefined] to QString
qrc:///ui-common/ui/RangeInputDialog.qml:39:10: Unable to assign [undefined] to QString
qrc:///ui-common/ui/RangeInputDialog.qml:58:19: Unable to assign [undefined] to double
qrc:///ui-common/ui/RangeInputDialog.qml:57:19: Unable to assign [undefined] to double
qrc:///ui-common/ui/RangeInputDialog.qml:56:12: Unable to assign [undefined] to double
qrc:///ui-common/ui/RangeInputDialog.qml:70:14: Unable to assign [undefined] to bool
qrc:///ui-common/ui/RangeInputDialog.qml:68:19: Unable to assign [undefined] to double
qrc:///ui-common/ui/RangeInputDialog.qml:67:12: Unable to assign [undefined] to double
有没有人知道这个问题。 我尝试在清晰的解决方案中使用相同的代码,然后效果很好。
解决方案
好吧,我不知道为什么编译器没有抛出任何警告,但是在 exec
方法中删除 const
说明符解决了这个问题。
最佳答案
当您加载 RangeInputDialog.qml 文件时,它会尝试访问 rangeDialogModel
上下文属性,但它尚不存在,从而导致那些未定义的警告。
此外,当您执行 QQmlContext context(&engine);
时,您正在创建一个新的上下文,而不是检索用于创建组件的上下文。
您应该通过调用 engine.getRootContext()
获得它然后对该上下文调用 setContextProperty
,以便您的组件可以访问上下文属性。
您应该执行 context.setContextProperty()
在 component.loadUrl()
之前。
附带说明:不是所有的 UI 都在 QML 中吗?从 C++ 显示 QML 对话框对我来说似乎很奇怪。 C++ 业务层不应该知道 QML UI 层。
关于c++ - QML [未定义] 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37181615/