0
votes

I have a several QWidgets, let's say previewWidget, that each consist of 2 QLabels (maybe more and other than QLabel). I want to drag and drop previewWidgets across the main window.

enter image description here

Problem: I can move the widget by pressing the mouse on the green area, which is PreviewWidget area. However, if I try to drag the widget by clicking on one of the labels, that label moves out the previewWidget (sometimes I don't even understand what happens). What I want is to move a whole previewWidget or at least nothing to happen when a mouse is pressed on its children.

My approach. I overloaded mousePressEvent() as follows:

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 ...
}

How to drag and drop PreviewWidget the way I want? Any examples are appreciated.

1
Did you try Qt::WA_TransparentForMouseEvents for the labels?SteakOverflow
I overloaded mousePressEvent() method of labels and left them blank. Now it does nothing when I drag the label and so far it is enough. Regarding your suggestion, I don't want them to be totally transparent to mouse events.Bobur

1 Answers

1
votes

I suggest a strategy for identifying the child at the cursor coordinates.

In your 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 ...
    }
}