Qt - Determine absolute widget and cursor position

前端 未结 3 615
半阙折子戏
半阙折子戏 2020-12-03 17:01

I have a QWidget that contains multiple children. The ultimate goal is to be able to drag and drop from one widget to the other, moving something between widgets. I\'ve go

相关标签:
3条回答
  • 2020-12-03 17:05

    Maybe you are looking for geometry() or frameGeometry() in QWidget. See here for more details.

    0 讨论(0)
  • 2020-12-03 17:13

    As already said you should rather use targetWidget->geometry() instead of contentsRect() in this special case.

    Next I wonder which class the code you posted belongs to. The method QWidget::mapToGlobal() should be invoked from the QWidget your coordinates are relative to. If I got you right, it should look like something like this:

    QRect widgetRect = targetWidget->geometry();
    widgetRect.moveTopLeft(targetWidget->parentWidget()->mapToGlobal(widgetRect.topLeft()));
    

    Then note QCursor::pos() is already returning global screen coordinates, so no need to map anything here:

    if (widgetRect.contains(QCursor::pos())) {
        /* swap widgets */
    }

    EDIT: Probably it's even better to not map the rect to global, but to map the global cursor position to the widget:

    if (targetWidget->rect().contains(targetWidget->mapFromGlobal(QCursor::pos()))) {
        /* do stuff */
    }
    0 讨论(0)
  • 2020-12-03 17:30

    This PyQt method will return True if the mouse position is within the widget's rect - including cases such as the mouse being over a combo view inside the widget

    def underMouse(self):
        pos = QtGui.QCursor.pos()
        rect = self.rect()
        leftTop     = self.mapToGlobal(QtCore.QPoint(rect.left(),rect.top()))
        rightBottom = self.mapToGlobal(QtCore.QPoint(rect.right(),rect.bottom()))
        globalRect = QtCore.QRect(leftTop.x(), leftTop.y(), rightBottom.x(), rightBottom.y() )
        return globalRect.contains(self.mapToGlobal(pos))
    
    0 讨论(0)
提交回复
热议问题