Parent child relationship of Qt window: Widget and button

Keywords: Windows

1. New project > other projects > empty qmake project: only one project program

1. New project - > other projects - > code snapped - > GUI application
 

2. Modify main.cpp: display a button on the main window: that is, set the parent window of the button to widget [because QPushButton inherits QWidget], so that the widget is associated with button. When the widget is shown, the show of button will be called.

#include <QApplication>
#include <QWidget>
#include <QPushButton>
int main(int argc, char *argv[])
{
    QApplication app(argc, argv);

    QWidget w;

    QPushButton button;   /*Buttons are windows*/
    button.setText("Button");
    button.setParent(&w);   //Parent child relationship of window object: set the parent window as button
   
    w.show();
    w.setWindowTitle("Hello world");
    w.show();
    return app.exec();
}

If the parent-child relationship is not set, the program has two main windows. The button window and the widget window have no relationship and are displayed separately:

#include <QApplication>
#include <QWidget>
#include <QPushButton>
int main(int argc, char *argv[])
{
    QApplication app(argc, argv);

    QWidget w;

    QPushButton button;   /*Buttons are windows*/
    button.setText("Button");
  //  Button. Setparent; / / parent-child relationship of window object: set the parent window as button
    button.show();  //Must
    w.show();
    w.setWindowTitle("Hello world");
    w.show();
    return app.exec();
}

3. Add signal and slot mechanism

#include <QApplication>
#include <QWidget>
#include <QPushButton>
int main(int argc, char *argv[])
{
    QApplication app(argc, argv);

    QWidget w;

    QPushButton button;   /*Buttons are windows*/
    button.setText("Button");
    button.setParent(&w);   //Parent child relationship of window object: set the parent window as button
    //Add signals and slots: when the clicked() function is called, close() is also called
    QObject::connect(&button, SIGNAL(clicked()), &w, SLOT(close()));
    w.show();
    w.setWindowTitle("Hello world");
    w.show();
    return app.exec();
}

The effect is that when the button is clicked, the window will exit.

 

 

--

Posted by samuraitux on Fri, 03 Jan 2020 00:42:58 -0800