Search code examples
c++qtqmlcollision-detectionqt-quick

Which is the best way for drawing graphics items with QML?


In my QML application I need common QGraphicsScene and QGraphicsObject possibilities like detect collision, "movable" and "selectable" flags, drag-and-drop etc. Should I inherit my classes from QQuickItem or use QML Canvas? Sure I'd like to write less code and choose a "QML-way".


Solution

  • For collision detection in QML you can use Box 2D QML plug-in. It has lots of good features and could be downloaded from here.

    You can also implement collision detection on your own. For example by checking this :

    Math.sqrt((ball1.x-ball2.x)*(ball1.x-ball2.x)+(ball1.y-ball2.y)*(ball1.y-ball2.y))<epsilon
    

    For making a QML item movable you can do something like :

    Image {
        id: icon
        width: 64
        height: 64
        source: "liverbird.gif"
    
        MouseArea {
            id: liverbirdMouseArea
            anchors.fill: parent
    
            property variant iconObj
            property int startX
            property int startY
    
            onPressed: {
                startX = mouseX
                startY = mouseY
                var iconComp = Qt.createComponent("icon.qml");
                iconObj = iconComp.createObject(parent);
                iconObj.x = mouseX - iconObj.width/2
                iconObj.y = mouseY - iconObj.height/2
            }
            onPositionChanged: {
                iconObj.x += mouseX - startX
                iconObj.y += mouseY - startY
                startX = mouseX
                startY = mouseY
            }
            onReleased: {
                iconObj.destroy()
            }
        }
    }