I have to create a C singleton class, but it doesn't work in qml.
#include "myimage.h"
MyImage::MyImage(QQuickPaintedItem *parent)
{
}
MyImage* MyImage::myImage = new MyImage;
MyImage *MyImage::instance()
{
return myImage;
}
void MyImage::paint(QPainter *painter)
{
QRectF target(10.0, 20.0, 80.0, 60.0);
QRectF source(0.0, 0.0, 70.0, 40.0);
painter->setRenderHint(QPainter::Antialiasing, true);
painter->setRenderHint(QPainter::SmoothPixmapTransform, true );
painter->drawImage(target, this->m_Image, source);
}
const QImage &MyImage::getM_Image() const
{
return m_Image;
}
void MyImage::setM_Image(const QImage &mimage)
{
if (mimage != m_Image) {
m_Image = mimage;
emit m_ImageChanged();
}
}//This is my singleton class.
Then I register it in main.cpp.
QObject *getMySingletonImage(QQmlEngine *engine, QJSEngine *scriptEngine)
{
Q_UNUSED(engine)
Q_UNUSED(scriptEngine)
return MyImage::instance();
}
...
qmlRegisterSingletonType<MyImage>("s0.image", 1, 0, "MyImage", &getMySingletonImage);
In QML:
import s0.image 1.0
MyImage{
}
I cannot run the program successfully.
qrc:/Camview_Page.qml:371:13: Element is not creatable.
Actually, I use the singleton class both in my backend and qml. In my backend, I will get QImage type images but not be saved local, so I cannot use QUrl and I only figure out this method.
Expectation: My backend pass images of QImage type to the singleton class, my singleton class realize the method of paint, my qml show the image.
BTW...my backend gets images from camera.
CodePudding user response:
A singleton is already created for QML so you get that error message since by using "{}" you are trying to create the object.
In this case it is enough to set a parent and the size:
import QtQuick 2.15
import QtQuick.Window 2.15
import s0.image 1.0
Window {
id: root
width: 640
height: 480
visible: true
title: qsTr("Hello World")
Component.onCompleted: {
MyImage.parent = root.contentItem
MyImage.width = 100
MyImage.height = 100
}
}
If you want to create a binding for example set anchors.fill: parent
then you can use the Binding
component, if you want to hear any signal then you must use Connections
component.
import QtQuick 2.15
import QtQuick.Window 2.15
import s0.image 1.0
Window {
id: root
width: 640
height: 480
visible: true
title: qsTr("Hello World")
Binding{
target: MyImage
property: "parent"
value: root.contentItem
}
Binding {
target: MyImage
property: "anchors.fill"
value: MyImage.parent
}
Connections{
target: MyImage
function onWidthChanged(){
console.log("width:", MyImage.width)
}
function onHeightChanged(){
console.log("height:", MyImage.height)
}
}
}