How to generate a window (widget) on button press in qt

16,902

You need signals and slots.

You have to connect the clicked signal to a custom slot, created by you, of your main widget.

Corrected Code, based in the comments of Patrice Bernassola and Job.

In the class definition (.h file) add the lines:

Q_OBJECT

private slots:
    void exampleButtonClicked();
private:
    QDialog *exampleDialog;

The macro Q_OBJECT is needed when you define signals or slots in your classes.

The variable exampleDialog should be declared in the definition file to have access to it in the slot.

And you have to initialize it, this is commonly done in the constructor

ExampleClass::ExampleClass()
{
    //Setup you UI
    dialog = new QDialog;
}

In the class implementation (.cpp file) add the code that does what you want, in this case create a new window.

void ExampleClass::exampleButtonClicked()
{
    exampleDialog->show();
}

And also you have to connect the signal to the slot with the line:

connect(exampleButton, SIGNAL(clicked()), this, SLOT(exampleButtonClicked()));

Your question is somehwat basic, so I suggest to read a basic tutorial, in this way you can make progress faster, avoiding waiting for answers. Some links to tutorials that were useful to me:

http://zetcode.com/tutorials/qt4tutorial/

http://doc.qt.io/archives/qt-4.7/tutorials-addressbook.html

Share:
16,902
Ram
Author by

Ram

Updated on June 22, 2022

Comments

  • Ram
    Ram about 2 years

    I have designed a GUI through Qt creator on Linux. This design consists of some fields, text edit and some push buttons.

    When I press on the push button I want to display another window. Is there any GUI option for this or any hard code?