如何拖放包含多个小部件的qwidget?

时间:2018-01-17 07:28:01

标签: c++ qt drag-and-drop qt5

我有几个QWidgets,让我们说 previewWidget ,每个都包含2个QLabel(可能更多,而不是QLabel)。我想在主窗口中拖放 previewWidget

enter image description here

问题:我可以通过在绿色区域(即PreviewWidget区域)上按鼠标来移动窗口小部件。但是,如果我尝试通过单击其中一个标签来拖动窗口小部件,那么该标签将移出 previewWidget (有时我甚至不理解会发生什么)。我想要的是移动整个 previewWidget ,或者当对其子项按下鼠标时至少没有任何事情发生。

我的方法。我重载了 mousePressEvent(),如下所示:

void MainWindow::mousePressEvent(QMouseEvent *event)
{
   // I beleive my problem is right here...
    PreviewWidget *child = static_cast<PreviewWidget*>(this->childAt(event->pos()));

    if (!child)
        return;    // this is not returned even if the child is not of a PreviewWidget type

    // Create QDrag object ...
}

如何以我想要的方式拖放PreviewWidget?任何例子都表示赞赏。

1 个答案:

答案 0 :(得分:1)

我建议在光标坐标处识别孩子的策略。

mousePressEvent

//...

QWidget * child = childAt(e->pos());
if(child != 0)
{
    QString classname(child->metaObject()->className());
    if( classname == "QLabel")
    {
        child = child->parentWidget();
        if(child != 0)
        {
            classname = child->metaObject()->className();
        }
    }
    if(classname == "PreviewWidget")
    {
        //do whatever with child ...
    }
}
相关问题