Adding QPushButton to Custom Widget on Mouse Press



  • I created a class that inherited QWidget. This widget would behave like a view that you could add buttons too and drag around. Then in the designer I made a QWidget and promoted it to my CustomWidget. Outside of the custom widget class, in the windows constructor, I can add buttons too my widget like so:

    QPushButton* testButton = new QPushButton(ui.transferFunctionWidget);
        testButton->setStyleSheet("QPushButton { background-color:rgb(218, 218, 218); border: none; } QPushButton:pressed { background-color:rgb(222, 237, 249); }");
        testButton->setGeometry(0, 0, 50, 50);
    

    But If I try to add a button too it from mousePressEvent, nothing happens. I can confirm the code is hit because I tested it with a breakpoint.

    void CustomWidget::mousePressEvent(QMouseEvent* event)
    {
        // When the widget is pressed add a button to it
        QPushButton* testButton = new QPushButton(this);
        testButton->setStyleSheet("QPushButton { background-color:rgb(218, 218, 218); border: none; } QPushButton:pressed { background-color:rgb(222, 237, 249); }");
        testButton->setGeometry(0, 0, 50, 50);
    }
    

    Why doesn't this behave as one would expect? How can I do it without a layout?


  • Lifetime Qt Champion

    Hi,

    I'd say missing call to the show function.


Log in to reply