Search code examples
c++qtqwidget

Creating QWidget in a class


I am trying to create a window in my class.

I went through the documentation : http://doc.qt.io/qt-5/qtwidgets-tutorials-widgets-toplevel-example.html

QApplication a(argc, argv);
QWidget window;
window.show();
return a.exec();

This does show the window when the code is in main.cpp .

But I want to create the window in other class. When I use the line :

QWidget window;
window.show();

It doesn't give me the window, and the program also doesn't quit.

So how can we create a widget in QT in our own class?


Solution

  • This a sample QWidget that initialized and customized:

    #include <QWidget>
    
    void FileManager::initializeMyWidget()
    {
        QWidget *myWidget= new QWidget();
        myWidget->setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint);
        myWidget->setWindowFlags(windowFlags() | Qt::CustomizeWindowHint | Qt::WindowStaysOnTopHint);
        QIcon iconMyWidget(":/Images/Images/image.png");
        myWidget->setWindowIcon(iconMyWidget);
        QHBoxLayout *mainLayout = new QHBoxLayout;
        myWidget->setLayout(mainLayout);
    }
    

    Now call function and show the widget:

    initializeMyWidget();
    myWidget->show();