最近,我遇到了一个小问题,即在QT中从cpp访问qml中的复选框。所以问题很简单:我有一个main.qml
文件,它有一个复选框,我想根据我在QSettings中保存的配置将“checked
”属性更新为true或false启动应用程序。目前,我在应用程序启动时已成功从cSet文件中的QSettings加载设置。那么如何修改此cpp文件中的“checked
”属性?
我尝试了这个:http://doc.qt.io/qt-5/qtqml-cppintegration-interactqmlfromcpp.html并使用了findChild
函数,但它不起作用。
1),我将import <QtQuick>
放在cpp文件中,但我收到QtQuick file can't be found
错误。
2),我改为“import <QtQuick/QQuickView>
”。已解决1)但此行QObject* object = view.rootObject();
出现了新错误:
cannot initialize a variable of type 'QObject *' with an rvalue of type 'QQuickItem *`
3),我将QObject* object = view.rootObject();
此行更改为QQuickItem* object = view.rootObject();
,然后使用QObject* acbox = object->findChild<QObject* >("acbox");
。 (acbox是该复选框的objectName)解决了2)但得到了新的错误:
Undefined symbols for architecture x86_64:
"QQuickView::setSource(QUrl const&)", referenced from:
ndn::TrayMenu::TrayMenu(QQmlContext*, ndn::Face&) in tray-menu.cpp.1.o
"QQuickView::QQuickView(QWindow*)", referenced from:
ndn::TrayMenu::TrayMenu(QQmlContext*, ndn::Face&) in tray-menu.cpp.1.o
"QQuickView::~QQuickView()", referenced from:
ndn::TrayMenu::TrayMenu(QQmlContext*, ndn::Face&) in tray-menu.cpp.1.o
"QQuickView::rootObject() const", referenced from:
ndn::TrayMenu::TrayMenu(QQmlContext*, ndn::Face&) in tray-menu.cpp.1.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
有人有什么建议吗?提前谢谢!
答案 0 :(得分:0)
您是否在参考QT页面中尝试了该示例?下面的例子将qml信号连接到C ++类的插槽,但我认为应该可以做反向:你连接C ++的变量信号谁想要复选框更新。然后它连接到QML的插槽,用于更新复选框。
int main(int argc, char *argv[]) {
QGuiApplication app(argc, argv);
QQuickView view(QUrl::fromLocalFile("MyItem.qml"));
QObject *item = view.rootObject();
MyClass myClass;
QObject::connect(item, SIGNAL(qmlSignal(QString)),
&myClass, SLOT(cppSlot(QString)));
view.show();
return app.exec();
}
答案 1 :(得分:0)
您可以在cpp中使用setproperty在qml中设置属性,然后将其绑定到qml文件中的已检查状态,请检查以下代码
int main(int argc, char *argv[])
{
QGuiApplication app(argc, argv);
QQmlApplicationEngine engine; QQmlComponent component(&engine, QUrl("qrc:/main.qml"));
QObject *object = component.create();
object->setProperty("checkstatus", false);
return app.exec();
}
in qml try this
Window {
visible: true
width: 640
height: 480
title: qsTr("Hello World")
property bool checkstatus
CheckBox {
id:checkbox
text: qsTr("checkbox1")
checked: checkstatus
}
}