Connect to qml file
-
Hello,
I have multiple qml files in one project. I want to connect a signal from a cpp-file to a slot in one of the qml files. My main qml file is the main.qml
The slot I want access is in the slots.qml file.Here is my code so far:
main.cpp
@
//.....
QGuiApplication app(argc, argv);
QtQuick2ApplicationViewer viewer;
viewer.setMainQmlFile(QStringLiteral("qml/App/main.qml");QObject::connect(&viewer, SIGNAL(button_pressed()), (QObject*)viewer.rootObject(), SLOT(button_pressed()));
viewer.showExpanded();
return app.exec();
@slots.qml
@
//...
Item {
width:1280
height:752
i d: gui_slots
//...
function button_pressed() {
console.log("Hello")
}
//...
}
@If I copy the function button_pressed() to the main.qml I connect it successfully with the signal. But in the slots.qml file I can't connect it with this code. What should I change or add?
Thank you for all answers!
-
Hi,
[quote]If I copy the function button_pressed() to the main.qml I connect it successfully with the signal. But in the slots.qml file I can’t connect it with this code.[/quote]That's because your viewer's rootObject() refers to main.qml. Remember, you called this:
@
viewer.setMainQmlFile(QStringLiteral("qml/App/main.qml");
@How does your main.qml access slots.qml?
-
[quote author="JKSH" date="1391616505"] How does your main.qml access slots.qml?[/quote]
Hey JKSH,
thank you for your fast answer.
I have defined states in the main.qml. Like this:
@
//...
slots{
id:gui_slots
}states: {
State {
name: "gui_slots_state"
PropertyChanges { target: gui_slots; visible:false; }
//...
}
//...
@ -
Hi,
That won't work. Only top-level functions can be accessed from outside the .qml file.
@
// main.qml
Rectangle {
id: topLevelRect
function topLevelFunc() {...}Rectangle { id: childRect function childFunc() {...} }
}
@
In the above, you can connect a C++ signal to topLevelFunc(), but you cannot connect to childFunc() because it is private. You have 3 options:Implement the slots in main.qml directly, and connect your C++ signal to them.
Implement "forwarding" slots in main.qml, and connect your C++ signal to them. Then, make these slots in main.qml call the functions in slots.qml.
"Give your child an objectName, and search for it in C++":http://qt-project.org/doc/qt-5/qtqml-cppintegration-interactqmlfromcpp.html#accessing-loaded-qml-objects-by-object-name. Warning: This is a NOT recommended technique. Programming this way can cause your projects to become difficult to maintain.
May I ask what you're trying to do? Why do you put your functions inside a separate slots.qml file?