2
votes

I want to create a QML Module with a python "backend" if that makes sense. Basically, I want to use QML do define how the component looks, and then implement specific behavior in a python class, which should extend this QML-Type and - in my imagination - somehow must be linkable to the QML component.

I understand how to create a custom class in python and making it available to QML via qmlRegisterType. This works so far, but then all the drawing has to be implemented in the class itself - no QML

(Basically, what I want is simliar to the way it is done in kivy with the kv-language)

A small example:

I implemented a simple ColorPicker widget like this:

class ColorWheel(QLabel):
    radius = 0

    color_changed = pyqtSignal(float, float)

    def __init__(self, width, height):
        super().__init__()

        pixmap = QPixmap("colorwheel.png").scaled(width, height)

        self.setFixedSize(width, height)
        self.setPixmap(pixmap)
        self.radius = width / 2

    def mouseReleaseEvent(self, event):
        # {...} get mouse position, calc polar corrdinates (omitted)
        # emit signal: new color was selected
        self.color_changed.emit(r, angle)

    def get_polar(self, x, y):
        # {...} calculate polar coordinates for HSV color space (omitted)
        return r, theta

Now I want move the GUI-code (pixmap-drawing and so on) to a QML file ColorWheel.qml like this:

import QtQuick 2.0
Item {
    Image {
        id: img
        anchors.fill: parent
        source: "./colorwheel.png"  
    }
}

In the main QML file main.qml I then want to do something like this:

import QtQuick 2.2
import ColorWheel 1.0

ApplicationWindow {
    title: qsTr("Test Invoke")
    width: 500
    height: 400

    ColorWheel {
        radius: 200
    }
}

Is this even possible? I could not find anything about this in the Qt and pyQt documentation. It's always about making C++ classes available to QML or the other way around...

Can someone point me in the right direction?

Many thanks!

1

1 Answers

1
votes

If you inherit from the QQuickItem and register it - it will obviously act like Item {}.

If you add some properties on the C++/python side - it'll be an Item with properties.

ColorWheelImpl.h (make a python equivalent):

class ColorWheelImpl: public QQuickItem
{
...
};
...
qmlRegisterType<ColorWheelImpl>("com.mycompany.myitems", 1, 0, "ColorWheelImpl");

In Python the qmlRegisterType syntax is something like:

qmlRegisterType(ColorWheelImpl, 'com.mycompany.myitems', 1, 0, 'ColorWheelImpl')

ColorWheel.qml:

import QtQuick 2.0
import com.mycompany.myitems 1.0
ColorWheelImpl {
    Image {
        id: img
        anchors.fill: parent
        source: "./colorwheel.png"  
    }
}