Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

Movable QWidget



  • I have created a graphical item containing a button and an editable text box, and I have added this item to an existing scene :
    0_1528632673411_stackoverflow.png
    But I want the whole item to be movable.
    I tried to use the setFlags method on the QGraphicsProxyWidget, but it doesn't work. Here is my code :

    QWidget widget;
    
        QPushButton* button = new QPushButton("Button1");
        QLineEdit *numberEdit = new QLineEdit;
    
        QFormLayout *layout = new QFormLayout;
        layout->addRow(button, numberEdit);
        widget.setLayout(layout);
    
        widget.setFixedSize(200,80);
    
        QGraphicsScene scene;
    
        QGraphicsWidget* proxy =  scene.addWidget(&widget);
    
        proxy->setFlags(QGraphicsItem::ItemIsMovable | QGraphicsItem::ItemIsSelectable);
    
        QGraphicsView view (&scene);
    
        view.show();
    

    So here's my question : do I have to create a custom QWidget class and reimplement the mouse event methods, or is there a simpler way to do this ?
    Thank you for your help.



  • Here is a good way to solve this problem:

    Resume of code (@rbaleksandar):

        // Create the rect to control the widget
        QGraphicsRectItem *proxyControl = scene.addRect(0, 0, widget.width(), 20, QPen(Qt::black), QBrush(Qt::darkGreen));
        proxyControl->setFlag(QGraphicsItem::ItemIsMovable, true);
        proxyControl->setFlag(QGraphicsItem::ItemIsSelectable, true);
    
        // Insert the widget
        QGraphicsProxyWidget *proxy = scene.addWidget(&widget);
        proxy->setPos(0, proxyControl->rect().height());
        proxy->setParentItem(proxyControl);
    


  • @KillerSmath This is great, thank you very much for the answer !


Log in to reply