How to open a new window using the button in the main window using Qt Creator?

This seems like a simple task, but I could not figure out how to do it. I have two windows developed in Qt Creator, one of which is designed to open when a button is pressed in the main window. Here is the code I'm trying to use to open it:

void MainWindow::on_generateDomain_clicked() { DomainGeneration dg; dg.show(); } 

DomainGeneration is the name of my window class. The header and source code for this have not been changed from the default Qt Creator I created. Am I doing something wrong? I do not get any errors, the window simply does not open when the button is pressed.

+6
source share
2 answers
 { DomainGeneration dg; // <-- automatic object dg.show(); // equivalent to setVisible(true) } // at this point dg is destroyed! 

One solution is to make dg a (private) data element of the MainWindow class.

QDialog has open() and exec() methods that show a dialog as a modal dialog. You probably assumed that this is the default behavior. In your case, however, dg is created and destroyed immediately.

+10
source

This is more thankyou to Nick Dandukakis than the answer. It was so helpful. I am such a noob that I would never have thought about destroying an object after the method has completed.

I declared (or instantiated ... or both?) My class in the header file for my main window (window.h), and then added the following functions to the slot in window.cpp:

 void Window::on_actionAbout_triggered() { Window::about.show(); Window::about.raise(); Window::about.activateWindow(); } 

I assume that this works because about the object previously created and therefore is not limited to the scope of the method or slot, which ends pretty quickly.

0
source

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


All Articles