Search code examples
c++qtqgraphicsview

How can i move the QWidget in QGraphicsView?


I want to move the QPushButton or kind of QWidget in QGraphicsView for example QListWidet, QTableWidget etc.

So, I used QGraphicsProxyWidget.

Then I clicked the widget and drag. But It is not moving.

How can i move QWidget?

This is my code.

ui->graphicsView->setGeometry(0,0,geometry().width(),geometry().height());
scene = new QGraphicsScene(0, 0, geometry().width(), geometry().height(), this);

ui->graphicsView->setScene(scene);

btn =new QPushButton(NULL);
QGraphicsProxyWidget *proxy = scene->addWidget(btn);
proxy->setFlags(QGraphicsItem::ItemIsMovable|QGraphicsItem::ItemIsSelectable);
scene->addItem(proxy);

Can you tell me What is wrong?

Thanks.


Solution

  • Cause

    In your case you cannot move the button, because although you have made the proxy movable, the button handles the mouse input differently in order to implement its clicked functionality. In other words, on a mouse press, how could a move action be differentiated from a click action?

    Solution

    My solution would be to make the button part of a somewhat bigger QGraphicsRectItem. The latter will serve as a draggable handle, i.e. if the user interacts with the button - it clicks, but if the other portion of the QGraphicsRectItem (not covered by the button) is interacted with, the button could be moved around.

    Example

    Here is an example showing exactly how to do that:

    auto *item = new QGraphicsRectItem(0, 0, 75, 40);
    auto *proxy = new QGraphicsProxyWidget(item);
    auto *btn = new QPushButton(tr("Click me"));
    
    btn->setGeometry(0, 0, 77, 26);
    
    item->setFlag(QGraphicsItem::ItemIsMovable);
    item->setBrush(Qt::darkYellow);
    
    proxy->setWidget(btn);
    proxy->setPos(0, 15);
    proxy->setFlags(QGraphicsItem::ItemIsMovable|QGraphicsItem::ItemIsSelectable);
    
    scene->addItem(item);
    

    Note: To make this work it is important to set the parent of proxy to item.