I created an Hello World app in QML. Now I want to learn how to modify the text from "Hello World" to "Goodbye World" from C++.
The qml looks like so:
import QtQuick 2.6
Rectangle {
property alias mouseArea: mouseArea
width: 360
height: 360
MouseArea {
id: mouseArea
anchors.fill: parent
}
Text {
id: helloText
anchors.centerIn: parent
text: "Hello World"
}
}
I've attempted to follow the
https://wiki.qt.io/Introduction_to_Qt_Quick#Integration_with_C.2B.2B_applications
But no luck. The code seems incomplete. For example, it leaves off information with ellipses like so:
QDeclarativeContext *context = …;
And I can't find the header for the QDeclarativeContext even if it didn't. I suspect the documentation is old, but I'm not sure.
Anyway, I just want to see a simple example that lets me change the text from "Hello World" to "Goodbye World" from inside a C++ program.
That code is for the old QtQuick1 API, which was based on QGraphicsScene and is now outdated, obsolete and IIRC removed from Qt.
I would recommend against mingling with QML from C++, I'd even go further and call it an anti-pattern, in 99.9999% of the cases there is a better solution. You should keep the interaction between C++ and QML to a well defined API.
That being said, it is still possible to find objects and manipulate their properties. You can use QQmlApplicationEngine::rootObjects() to get access to the root objects, from there you can findChild() any object you have provided a objectName on the QML side, you can use QMetaObject:invokeMethod() (works for QML functions too!), use qobject_cast, set properties and whatnot.
All those techniques are covered in the documentation.
Related
Basically, I have something like:
Main.qml:
ApplicationWindow{
width: 500
height: 500
Page{
id: page0
DataPage{
id: datapage0
}
}
}
DataPage.qml:
Page{
id: displayPage
DataDisplay{
id: dataShow
}
}
DataDisplay.qml:
Label{
text: "data: "
}
TextArea{
id: dataArea
text: ""
}
I've removed the stuff I think isn't relevant (such as anchors, height, width, etc.). Now, in main.qml, I have a signal coming from the c++ backend:
Connections{
target: modb
onPostData: {
page0.datapage0.dataShow.dataArea.text = string;
}
And I get the following error:
TypeError: Cannot read property 'dataArea' of undefined
So, I wanted to ask: how do I connect that signal to the child object that is defined in DataDisplay.qml? I'm able to get info into main.qml using signals, but seem to be unable to dereference child objects
Edit:
main.cpp:
QQmlContext* ctx0 = engine.rootContext();
ctx0->setContextProperty("ark", &ark);
QQmlContext* ctx1 = engine.rootContext();
ctx1->setContextProperty("comm", ark.comm);
QQmlContext* ctx2 = engine.rootContext();
ctx2->setContextProperty("modb", ark.modb);
is how I set the Context (of 3 classes, as you can see). I'm able to get signals from any of the three into main.qml, as well as call slots in any of the three in main.qml; I haven't yet tried to call slots from the c++ classes in the other qml files, but I assume it would work because I can access the parent's properties from the child
1 - you have 3 pointers pointing to the same object. One is enough. Really!
2 - as long as ark is properly implemented, you can access ark.comm and ark.modb from QML, no need to expose them individually.
3 - you don't seem to understand the scope of ids. Take a look at this exhaustive answer. dataShow is simply not visible from wherever you made the connection.
4 - context properties are not very efficient, that's more of a "quick and dirty" approach to expose C++ to qml. For optimal performance consider a more efficient approach.
All in all, you exhibit the typical symptoms of "getting ahead of yourself". Take the time to learn before you practice.
As you indeed assume you can use the modb variable in the other qml's as well, since it is added to the rootContext. I would advise this option.
Another option you could try is just using dataArea.text = string since the id's go all over the place (it's javascript after all), you should use strong id's in this case.
Another option is to define property alias's to pass the string through over the objects (See Qt docs). Or use property string, but that's even more work.
I have a application and I want make a little animation for it.
I did a qml file and used QQuickWidget to open and show it in my display. Now a I want make iteration between c++ and QML. I want, for example, when a function in c++ is called, a ball move in my display. But I could not make a connection between c++ and qml.
Every help is welcome.
A little part of my code:
c++
QQuickWidget *quickWidget = new QQuickWidget;
quickWidget->setSource(QUrl("qrc:/QML/main.qml"));
auto rootObject = quickWidget->rootObject();
// Connect C++ signal to QML slot
connect(this, SIGNAL(cppSignal()), rootObject, SLOT(qmlSlot()));
emit cppSignal();
QML
Rectangle {
id: tela
visible: true
width: 715
height: 77
color: '#E8E8E8'
// NumberAnimation {
// running: true
// target: bolinha
// property: "x"
// duration: 1000
// to: 600
// }
function qmlSlot() {
bolinha.visible= enabled
animBolinha.start();
}
}
enter image description here
What I can do to solve it?
I am not sure if you can call a QML method from C++ code as you did.
The recommended way from QT documentation is:
All QML methods are exposed to the meta-object system. As the functions are exposed to meta-object system, you can use QMetaObject::invokeMethod(), to invoke the QML function.
Probably in your case, you should call as said below (not tested).
auto rootObject = quickWidget->rootObject();
QMetaObject::invokeMethod(rootObject, "qmlSlot");
Look documentation (search for Invoking QML Methods)
As said in documentation, you can use Q_ARG to pass the arguments and Q_RETURN_ARG for receiving return arguments.
I'm working on a C++ Qt project that will eventually communicate with the serial port. One part of this is accessing QML objects in the C++ portion. I have code that can set properties of the QML, but accessing those features that are methods now has me stumped. View the following code:
object = view.rootObject();
rect = object->findChild<QObject *>("box");
rect->setProperty("color", "red"); // Verifies the object tree is accessible
viewer = object->findChild<QObject *>("viewer"); // Access the viewer text box
viewer->append("dummy text"); // OOPS! This doesn't compile!!!
Now, the type as a method setProperty(..), but how do you access methods of an object. "viewer" is a TextArea and I want to first do a selectAll(), then a cut() to clear the box.
The question here is how is this coded? Thanks all.
Of course it would not compile, QObject doesn't have an append() method.
If it is a C++ function, you will have to qobject_cast to the appropriate type that has it. This however is not always readily available for many of the stock QML types that are implemented in C++, and as C++ types they are not part of the public API and not generally intended for direct use by an end user.
If it is a JS function, you will have to use QMetaObject::invokeMethod. That will also work for C++ functions for which meta data has been generated. Which is also how setProperty() works, whereas setColor() would not work with a QObject* much like append() doesn't.
Last but not least, there is absolutely no good reason for you to be doing those kinds of things from C++. Using QML objects from C++ is poor design and an anti-pattern. You will only develop bad habits trying to do that. Such interactions must be limited to a clearly defined interface using signals, slots and properties. Generally speaking, it is OK for QML to reach into C++, because that only happens through an exposed interface, but the opposite way, even if possible, should not utilized.
Think of it like this - a car uses the engine, the engine doesn't use the car. And the engine control is interfaced through the starter key and the gas pedal, it is not used directly. The C++ stuff should be reserved to the application engine - the high performance or efficiency core logic, or the back-end, whereas the QML part is for the GUI/front-end.
The author's QML part may expose alias property to operate with desired text field content:
import QtQuick 2.0
import QtQuick.Controls 1.2
Item {
property alias viewerText: viewer.text // added
width: 350
height: 450
TextArea {
id: viewer
x: 8
y: 8
width: 223
height: 415
text: "text"
font.pixelSize: 12
objectName: "viewer"
}
Button {
id: open
x: 251
y: 8
text: "Open"
}
}
And then the author's C++ part can easily do:
auto* object = view.rootObject();
viewer = object->findChild<QObject *>("viewer");
viewer->setProperty("viewerText", "dummy text"); // using the new property added
Using the posted answer here using the invoke method, here's the solution that works:
// C++ Code to call function reset()
QMetaObject::invokeMethod(object, "reset");
// QML code to select all text the delete it
function reset() {
viewer.selectAll()
viewer.cut()
}
There's another question on Stackoverflow about this matter but I don't find the accepted solution possible. So I ask again because the old question is out of attention.
The situation is this way. I have application screens defined by 'main.qml', 'feature1.qml', 'feature2.qml'.
These screens share the same toolbar below title bar. The toolbar has multiple items so copy-paste the QML code is like crazy. This question: QML file include - or one monolithic file (structure QML code)? says it's possible to just use QML file name as component name but I can't get it working.
Any solution? with details pls.
Let's assume you have a file called main.qml and a component in another file called MyCustomText.qml. If both files are in the same directory you can directly load the component like this:
// in Main.qml
Rectangle {
id: root
MyCustomText {
text: "This is my custom text element"
}
}
If MyCustomText.qml is in another subdirectory MyComponents for example to group all your custom components together, you first need to import the directory before using the component the same way:
// in Main.qml
import "MyComponents"
Rectangle {
id: root
MyCustomText {
text: "This is my custom text element"
}
}
Another important thing to note is that your QML files should always start with an uppercase letter if you want to be able to use them this way
Of course your Loader solution works too but this is the easiest way to import QML files in other components.
Finally I have dug it out from internet. Let's say the to-be-included file is 'mycomponent.qml' in this directory structure (Qt Quick):
projectdir/
qml/
projectname/
main.qml
mycomponent.qml
The content of 'mycomponent.qml' (for example):
Text {
text:"Hello, Scooby Doo!";
}
We have to load it this way (in 'main.qml'):
Rectangle {
...
Loader {
source:"mycomponent.qml";
}
...
}
See Qt documentation about reuseable components.
The imported QML file defines a type whose name is the same as the filename (capitalized, less the .qml suffix). QML calls the type a reuseable component. You use that type name to instantiate an object in the importing QML document (file.)
Its not like a C language include, where the text of the included file is inserted into the including file. Its more like importing the name of a class in Python, and then instantiating an object of that class in the importing file. Or somewhat similar to Javascript, the imported file is creating a prototype object, and the importing file is prototypically inheriting from it. Except note the discussion about the root object and what properties of the component will be visible (because of QML's document scoping.) You won't be able to access everything in the imported file as if it were a C include, a Python import, or a JS inheritance.
It's easy like that. Put all your file components in a folder like "components". In your case, the name of the file can be Toolbar.qml. Write the QML code for you toolbar, my example will draw a red rectangle.
import QtQuick 2.6
Item {
width: 500
height: 100
Rectangle {
width: 500
height: 100
color: "red"
radius: width * 0.5
}
}
And then, in your screens which you want to use this component (for example, file main.qml), is simple like that:
import "components" as Components
Components.Toolbar {
Layout.fillHeight: true
}
Take care about the location of files, and still all components should start with a Caps letter, in this example:
\main.qml
\components\Toolbar.qml
You can just call the Name of the qml.
for ex.
I have 2 qml file.
The main.qml and Merchant.qml
I just called the Merchant. it should be showed in intellisense.
ApplicationWindow {
id: mainWindow
visible: true
Component{
id: merchantsComponent
Merchant{
id: merchants
width: mainWindow.width
height: mainWindow.height
}
}
}
You can just call that compenent to Loader
You can directly call:
Window {
id: mainWindow
visible: true
Feature1{}
}
like this, to load Feature1.qml
I'm trying to use a qml-grid view in my code. I'm trying to couple it with my C++ code.
I've dynamically created a list view model and passed across the qml file. It works fine.
However, I'm facing trouble when I want to connect a Qml signal to Qt/c++ code. I've handled mouseArea in my Qml-rectangle and emitting a signal from there.
I'm trying to connect to the signal as follows:
QDeclarativeView *pQMLContainer = NULL;
TempWidget *pTemp = new TempWidget();
pQMLContainer = new QDeclarativeView(pTemp);
pQMLContainer->setResizeMode(QDeclarativeView::SizeRootObjectToView);
pQMLContainer->rootContext()->setContextProperty("imgModel", createModel() );
pQMLContainer->setSource(QUrl("../Temp/qml/gridview-example.qml"));
QObject *rootObject = dynamic_cast<QObject*>pQMLContainer->rootObject();
QObject::connect(rootObject, SIGNAL(keyPressed()), pTemp, SLOT(onKeyPressed()));
When the connect statement runs, I get an error: cannot connect to "null" object.
On debugging, I found I could never get "rootObject" as a valid pointer.
Where am I going wrong?
Thanks
Can you try this ? (it is example code from Qt Docs)
QObject *item = pQMLContainer->rootObject();
QObject::connect(item, SIGNAL(keyPressed()),
pTemp, SLOT(onKeyPressed()));
The code is pretty much straight:
in .cpp file:
ui->declarativeView->setSource(QUrl("qrc:/Resources/main.qml"));
QGraphicsObject *obj = ui->declarativeView->rootObject();
connect ( obj, SIGNAL(clicked()), this, SLOT(itemClicked()));
and QML File:
import Qt 4.7
Rectangle {
width: 100
height: 100
id: rect
signal clicked
Text {
text: "Hello World"
anchors.centerIn: parent
}
MouseArea {
anchors.fill: parent
onClicked: {
rect.clicked();
}
}
}
one more thing, check the location of your qml file, it should be accessible to the binary.
Perhaps you should use qobject_cast instead of dynamic_cast? See e.g. question
dynamic_cast returns NULL but it shouldn't
QGraphicsObject is a QObject so no cast should be required. If your compiler complains, try adding #include <QGraphicsObject>.
Just casting without the compiler knowing the classes is asking for trouble. (Especially as there is multiple inheritance involved.)
I could finally get this working. I'm not sure if this is the real solution to the problem, but finally this got it working:
I was setting the qml path as a relative path to my working folder. And yes the path was indeed correct, as I could see the qml and its contents. I just happened to change the qml path from relative to the working folder to relative to "qrc" as:
pQMLContainer->setSource(QUrl("qrc:/gridview-example.qml"));
instead of:
pQMLContainer->setSource(QUrl("../Temp/qml/gridview-example.qml"));
and it started working. I'm not sure if I had to add the qml to the qrc (I've just started using qml).
Thanks everyone for your support!
Mots