Qt - Determine absolute widget and cursor position

前端 未结 3 702
半阙折子戏
半阙折子戏 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: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 */
    }

提交回复
热议问题