Simple parent and child window question
-
I am trying to create a window which shows a child window as soon as it is created, I am using the following code in main.cpp:
@#include <QtGui>
#include <QApplication>int main(int argc, char *argv[])
{
QApplication a(argc, argv);QWidget mainWindow; QWidget *popup = new QWidget(&mainWindow); mainWindow.show(); popup->show(); return a.exec();
}@
Problem is, the main window shows but the child popup window does not. I think I'm missing something obvious but can't figure out what it is. Please could someone help.
-
When you call mainWindow.show(), it automatically shows all its children. you don't need to call popup->show() again.
And your mainWindow or popup are just empty QWidgets. They don't have any content. Create some widgets like button and added them to your mainWindow or popup. Then you can see something.
-
The widget you named "popup" is just an sub widget of "mainWindow" instead of an real Popup Window.
If you want an Popup Window, you can use QDialog.
-
Thank you both for your quick responses, that's sorted it:
@#include <QtGui>
#include <QApplication>int main(int argc, char *argv[])
{
QApplication a(argc, argv);QWidget mainWindow; mainWindow.show(); QDialog popup(&mainWindow); popup.show(); return a.exec();
}@
I'm guessing when QWidget is instantiated without a parent it defaults to creating a window which shows automatically, but when a parent is given in the constructor it assumes that it's not a window and that the parent will handle its display. Does that make sense?
-
[quote author="donturner" date="1310118497"]
I'm guessing when QWidget is instantiated without a parent it defaults to creating a window which shows automatically, but when a parent is given in the constructor it assumes that it's not a window and that the parent will handle its display. Does that make sense?[/quote]yes you are true.
How you can display for example is to add a button to main window, and connect button clicked signal to popup open() ( not show() ) function.
-
QWidget *popup = new QWidget(&mainWindow); Means that popup widget will be a sub componnet of the mainWindow.
If you expect to see two seperate widgets show up at the same time, do like this:
@int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QWidget mainWindow;
//QWidget *popup = new QWidget(&mainWindow);
QWidget *popup = new QWidget(); // do not set mainWindow as its parent
mainWindow.show();
popup->show();
return a.exec();
}
@