How to drag a qquickwidget?

212 views Asked by At

I have a QQuickWidget inside main window. This seems to work, however, it will shake violently when dragged.

//main.qml
Rectangle{
      id: root
      property point dragStart
      signal moved(point offset)

      MouseArea{
          id: dragArea
          anchors.fill: parent

          onPressed: root.dragStart = Qt.point(dragArea.mouseX,dragArea.mouseY)
          onMouseXChanged: move()
          onMouseYChanged: move()
          function move(){
                var offset = Qt.point(dragArea.mouseX-root.dragStart.x, dragArea.mouseY-root.dragStart.y)
                root.moved(offset)
                console.log(offset)
          }
      }
}
//MainWindow.cpp
void MainWindow::moveQml(QPointF offset){
    ui->quickWidget->move(ui->quickWidget->pos()+offset.toPoint());
}

Here is the debug output when I only drag to the bottom left, the point shouldn't have positive x:

qml: QPointF(6, 2)
qml: QPointF(6, 2)
qml: QPointF(-6, -1)
qml: QPointF(-6, -1)
qml: QPointF(5, 1)
qml: QPointF(5, 1)
qml: QPointF(-5, 0)
qml: QPointF(-5, 0)
qml: QPointF(4, 0)
qml: QPointF(4, 0)
qml: QPointF(-5, 1)
qml: QPointF(-5, 1)

1

There are 1 answers

0
Zen On

Oh, I see. After checking the output, I know what's wrong. When moving the mouse, the mouse usually changes its x and y. So the move() will get executed twice.

onMouseXChanged: {
    var offset = Qt.point(dragArea.mouseX - root.dragStart.x, 0)
    root.moved(offset)
}

onMouseYChanged: {
    var offset = Qt.point(0, dragArea.mouseY - root.dragStart.y)
    root.moved(offset)
}