Qt: QPushButton never appears

I am trying to learn Qt with a fairly simple application:

#include <QtGui/QApplication>
#include <QPushButton>
#include <QDebug>

/* -- header begin {{{ */
class BareBase {
    public:
        BareBase();
};

class BareBones: public QApplication {

    private:
        BareBase* base;

    public:
        BareBones(int &argc, char **argv);
        ~BareBones();
};
/* -- header end }}} */


/* -- implementation begin {{{ */
BareBase::BareBase()
{
    QPushButton hello("Hello world!");
    hello.resize(100, 30);
    hello.show();
}

BareBones::BareBones(int& argc, char** argv): QApplication(argc, argv)
{
    qDebug() << "Creating new instance ... ";
    base = new BareBase();
}

BareBones::~BareBones()
{
    qDebug() << "Cleaning up ... ";
    delete base;
}

/* -- implementation end }}} */

int main(int argc, char **argv)
{
    //Q_INIT_RESOURCE(files);
    BareBones app(argc, argv);
    return app.exec();
}

Now the problem is that the button created in BareBasenever appears, and I am puzzled why?

+3
source share
2 answers

Your QPushButton creates and displays correctly, but goes beyond the scope of exiting the BareBase constructor. Using a member variable or pointer will solve your problem.

If you use a pointer, you must add your button to your parent. Thus, the button will be automatically deleted when the parent is removed.

+5
source

QPushButton , . , Qt, . ... ...

, QWidget , , QMainWindow, . , QPushButton . QApplication , โ€‹โ€‹ , ....

, .

-1

Source: https://habr.com/ru/post/1762808/


All Articles