Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct
Failed to convert QObject to QLabel.
I am trying to interact with QML Objects from C++. Now I have a main UI and child UI on Qt. the child UI can be embedded in main UI. Then, I want to load the Qml file on child UI. After that, I want to load image by using cv::Mat on the label object in Qml file.
This is my QML file.
And this is my C++ code.
The reason why I used a container to load quick view is I can embed the child UI on main UI easily by using addWidget().
Now I can access the label in Qml by using:
QObject *root = view2->rootObject(); QObject *label = root->findChild<QObject*>("label");
Since setPixmap() only works for QLabel, I try to convert QObject to Qlabel. My idea is using qobject_cast, but I failed. The label2 always be null. I have added Q_OBJECT already. So I think the issue isn't the header file.
I will appreciate it if anyone can help me!
QLabel is a QWidget, Label is a QQuickItem. They are (almost) unrelated. They use completely different painting methods. No matter how hard you try, you won't convert one to another.
If you want to set some data in QML from C++, use the proper APIs:
docs. For a simple image setting, you can just set up a root context property and set it in C++.
Thanks for your reply!
But I think I initialized label as a QObject here. The last figure proves the type of label is QObject.
And I have checked the usage of qobject_cast.
Since QLabel inherits QObject indirectly, I think qobject_cast should work. However, the fact is quite opposite.
Please, read up on how casting works. It won't magically make a QLabel out of your QQuickItem. You can continue along that path, but I tell you it's futile. You'll only waste time.
Actually you do not need to cast anything here. Your "label" object is a QObject, and it has properties. Use them! You can set "width" property on that QObject directly - and QML engine will understand it.
I can set "width" property on QObject directly, that's true, but that's not what I want. My aim is to display Mat image on label. As shown below, setPixmap doesn't work if label is a QObject.
This is the reason why I want to change the type of label. Of course, this may not be a good idea. If you have other way that can accomplish my aim, please tell me.
QML Label component does not have any image printing capability. Use an Image component instead. You can set "source" property to set the image (if you have it saved on a disk). If you need to provide an image without saving it to disk, you have 2 options:
- use custom image provider
- implement your own QQuickItem and do your own painting (into a texture)
Thank you! I will try first.