所以我可以通过C ++代码更改某个QML对象的属性,但是我无法在屏幕上看到结果。 我有一个重复64次的项目,我希望某个图像只显示第32个项目(来自C ++)所以我使用invokeMethod通过C ++访问该对象然后我使用setProperty来改变可见性,如果我查看它qDebug属性“可见”确实发生了变化,但我注意到屏幕上没有区别我仍然无法看到图像,但如果我从qml更改可见性,我可以看到它。
这是C ++代码:
int main(int argc, char *argv[])
{
QGuiApplication app(argc, argv);
QQuickView view;
view.setSource(QUrl("qrc:///main.qml"));
view.show();
QQuickItem* child;
QQmlApplicationEngine engine;
engine.load(QUrl(QStringLiteral("qrc:///Board.qml")));
QObject *rootObject = engine.rootObjects().first();
QQuickItem *qmlObject = rootObject->findChild<QQuickItem*>("grid")->findChild<QQuickItem*>("repeter");
QMetaObject::invokeMethod(qmlObject,"itemAt",Qt::DirectConnection, Q_RETURN_ARG (QQuickItem*,child), Q_ARG(int,32));
child=child->findChild<QQuickItem*>("pleaseWork");
qDebug() << child->property("visible");
child->setProperty("visible","true");
qDebug() << child->property("visible");
return app.exec();
}
我使用qDebug验证属性已更改
这是QML代码:
Item
{
id: root
width: 8*45
height: 8*45
Grid
{
id: grid
objectName: "grid"
rows: 8
Repeater
{
objectName: "repeter"
model: 64
Image
{
objectName: "test"
width: 45; height: 45
source: "images/dark_square.png"
Image
{
id: isit
objectName: "pleaseWork"
visible: false
source: "images/avail_dark.png"
}
}
}
}
}
答案 0 :(得分:1)
QQuickView
和QQmlApplicationEngine
是加载和显示QML视图的替代方法。您加载到QQmlApplicationEngine
的内容与QQuickView
的可见输出无关。
为了让事情顺利进行,您需要将QML文件的顶部元素从Item
更改为Window
并在屏幕上显示:
QQmlApplicationEngine engine;
engine.load(QUrl(QStringLiteral("qrc:///Board.qml")));
// end of your code
QObject *rootObject = engine.rootObjects().first();
QQuickWindow *window = qobject_cast<QQuickWindow *>(rootObject);
if (!window) {
qDebug() << "Error: Your root item has to be a window.";
return -1;
}
window->show();
// continue with your code
QQuickItem *qmlObject = rootObject->findChild<QQuickItem*>("grid")->findChild<QQuickItem*>("repeter");