How would I open a new window from a button in the main window using Qt Creator?
This seems like a simple task, but I haven't been able to figure out how I would do it. I have two windows designed in Qt Creator, one of which is meant to open when a button is pressed in my main window. Here is the code I am trying to use to open it:
void MainWindow::on_generateDomain_clicked()
{
DomainGeneration开发者_JS百科 dg;
dg.show();
}
DomainGeneration is the name of my window's class. The header and source code for this have not been altered from the default Qt Creator generated for me. Am I doing something wrong? I don't get any errors, the window just doesn't open when the button is pressed.
{
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 member of the MainWindow
class.
QDialog
has open()
and exec()
methods which show the dialog as a modal dialog. Probably you assumed that it was the default behavior. In your case though, dg
gets created and destroyed immediately.
This is more of a "thank you" to Nick Dandoulakis than it is an answer. That was so helpful. I'm such a noob I would have never thought about the object being destroyed after the method ends.
I declared (or instantiated... or both?) my about class in the header file for my main window (window.h), then added the following functionality to the slot in window.cpp:
void Window::on_actionAbout_triggered()
{
Window::about.show();
Window::about.raise();
Window::about.activateWindow();
}
I guess this works because the about object is previously instantiated and so isn't limited to the scope of the method or slot which terminates quite quickly.
精彩评论