Displaying widgets in a second Dialog
-
Hi,
Besides the mainwindow I have a dialog too. I added a QLabel to the mainwindow and it worked OK. The same code didn't work in the dialog; nothing was displayed.
#include "dialog.h" #include "ui_dialog.h" Dialog::Dialog(QWidget *parent) : QDialog(parent), ui(new Ui::Dialog) { ui->setupUi(this); QLabel *label = new QLabel; label->setText ("Test"); label->show (); } Dialog::~Dialog() { delete ui; } `` What did I do incorrectly? Thank you for all your help.
-
Hi,
Since you are not putting the widget in a layout, you should also position it yourself to be somewhere visible. Not that this way you have a memory leak. And if you used the same technique in your main window, then you have several memory leaks.
-
Hi @SGaist ,
I modified the code to include a QHBoxLayout, but it still doesn't show:
#include "dialog.h" #include "ui_dialog.h" Dialog::Dialog(QWidget *parent) : QDialog(parent), ui(new Ui::Dialog) { ui->setupUi(this); QWidget *dialog = new QWidget; QLabel *label = new QLabel; label->setText ("Name: "); label->show (); QLineEdit *lineedit = new QLineEdit; QHBoxLayout *HLayout = new QHBoxLayout(this); HLayout->addWidget (label); HLayout->addWidget (lineedit); dialog->setLayout (HLayout); dialog->show (); } Dialog::~Dialog() { delete ui; }
What's missing? Thank you for your help.
-
There are 2 type of widgets :
-
window type: dialogs , view, main window. You usually show them with show().
example:
Dialog* dlg = ...;
// can be shown as modeless
dlg->show();
// or modal:
dlg->show(); -
controls: such normally do not have to have their own window
The best way to dial with them is to put them in you window type widget layout.
There is no need to call show() for them.
If you do not want to us layout, you will have to position and show them within paint.
Your code as is, in constructor of Dialog:
a) creates instance of QWidget,
QWidget *dialog = new QWidget;
b) creates 2 controls lineedit and label
c) adds them to layout (HLayout )
d) sets layout to QWidget instance named dialog.First all show calls there are meaningless, just remove them.
If you did not have ui I would say that
main problem is that Dialog has no any relation to variable 'dialog'
and constructor should have looked like:Dialog::Dialog(QWidget *parent) :
QDialog(parent)
{
QLabel *label = new QLabel;
label->setText ("Name: ");
QLineEdit *lineedit = new QLineEdit;QHBoxLayout *HLayout = new QHBoxLayout(this); HLayout->addWidget (label); HLayout->addWidget (lineedit); this->setLayout (HLayout);
}
but seen a ,
ui(new Ui::Dialog)
line I assume you already defined all controls you need in QtDesigner,
In this case you better define layout there. -
-
Hi @alex_malyu ,
Thank you for the detailed explanation. It makes more sense now.