Check if an object of QPushButton has been created?

  • I create a QPushButton in my .h using the following code

    QPushButton *global_button;

    It's in my .h since different functions access it and modify it in different ways. The issue I got is that there is a probability that I don't create a global_button using

    global_button = new QPushButton(this);

    but rather do something like

    if(global_button->text() == "end") {
        qDebug() << "End.";

    before even implementing global_button. If I try to call global_button before global_button = new QPushButton(this); then the program crashes. Is there a way to circumvent this? AKA to check if there is a new instance of global_button?

  • Lifetime Qt Champion

    @legitnameyo said in Check if an object of QPushButton has been created?:


    Since it's a pointer you should properly initialize it to nullptr in the ctor and the you can check if it's still a nullptr or not - c++ basics.

  • //in .h
    QPushButton *global_button = nullptr;
    //in .cpp
    if(global_button == nullptr { /* actions */}

    worked! Thanks!

Log in to reply