Recently, I got a small problem, which is accessing the checkbox in qml from cpp in QT. So the problem is quite simple: I have a main.qml
file, which has a checkbox, I want to update the "checked
" property to true or false based on the configuration that I saved in QSettings when I launch the application. Currently, I have successfully load the setting from QSettings in cpp file when application startup. Then how to modify the "checked
" property in this cpp file?
I tried this :http://doc.qt.io/qt-5/qtqml-cppintegration-interactqmlfromcpp.html and used the findChild
function but it does not work.
1), I put import <QtQuick>
in cpp file but i got error as QtQuick file can't be found
.
2), I changed to "import <QtQuick/QQuickView>
". Solved 1) but got new error for this line QObject* object = view.rootObject();
:
cannot initialize a variable of type 'QObject *' with an rvalue of type 'QQuickItem *`
3), I changed QObject* object = view.rootObject();
this line to QQuickItem* object = view.rootObject();
and used QObject* acbox = object->findChild<QObject* >("acbox");
after that. (acbox is the objectName of that checkbox) Solved 2) but got new error:
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)
Anyone has any suggestion? Thanks in advance!
you can use setproperty in cpp to set a property in qml and then bind that to the checked status in qml file check the following code
C++ part:
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();
}
QML part:
Window {
visible: true
width: 640
height: 480
title: qsTr("Hello World")
property bool checkstatus
CheckBox {
id:checkbox
text: qsTr("checkbox1")
checked: checkstatus
}
}