QPushButton cannot be clicked when being created in MainWindow's constructor



  • I have a simple MainWindow class like this:

    #include <QMainWindow>
    #include <QPushButton>
    
    class MainWindow : public QMainWindow
    {
        Q_OBJECT
    
    public:
        explicit MainWindow(QWidget *parent = 0);
        ~MainWindow();
    
    private:
        Ui::MainWindow *ui;
        QPushButton       *button1,
                          *button2,
                          *button3,
                          *button4,
                          *button5;
    
    
    };
    

    And create the five buttons in MainWindow's constructor:

    MainWindow::MainWindow(QWidget *parent) :
        QMainWindow(parent),
        ui(new Ui::MainWindow)
    {
        QPushButton* button = new QPushButton("Random button",this);
        button->move(100,50);
    
        button1 = new QPushButton("One",this);
        button2 = new QPushButton("Two",this);
        button3 = new QPushButton("Three",this);
        button4 = new QPushButton("Four",this);
        button5 = new QPushButton("Five",this);
        button1->move(0,0);
        button2->move(0,50);
        button3->move(0,100);
        button4->move(0,150);
        button5->move(0,200);
    
    
        ui->setupUi(this);
    }
    
    
    

    These five buttons and the random button above show up but the mouse cannot click them. However, when I create a button in design mode and another one in main() function. These two buttons can be clicked:

    
    int main(int argc, char *argv[])
    {
        QApplication a(argc, argv);
    
        MainWindow mainwindow;
        QPushButton* clickableButton = new QPushButton("Clickable",&mainwindow);
        clickableButton->move(400,200);
    
    
        mainwindow.show();
    
        return a.exec();
    }
    
    

    Could anyone help me with this problem?

    Screenshot: Screenshot



  • Hi, and welcome to the Qt forum!

    That's because you first create these "unclickable" buttons and then setup the rest of the UI. By doing so these buttons are under the central widget of your form and thus the central widget gets all the clicks. So, just change the order to:

    ui->setupUi(this);
    QPushButton *button1 = new QPushButton("One",this);
    // ...
    


  • @Wieland It works. Maybe I did not fully understand the usage of the setupUi() function. Thank you very much.


  • Qt Champions 2016

    @khanhnguyen29 said:

    setupUi

    This function set up all widgets u placed visually in the UI file.
    It simply new and setup the widgets as was described by the UI file.
    Including MainWindow.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.