I'm constructing UI in QT programatically. The problem is when making a Qframe
, setting into a layout and adding the layout to my main window, the frame becomes a window of it's own. I've searched around but I can't seem to get it to become a frame within my main window.
MainWindow::MainWindow()
{
QWidget::showMaximized();
frame = new QFrame();
layout = new QHBoxLayout();
button = new QPushButton("Push");
layout->addWidget(frame);
frame->show();
this->setLayout(layout);
Setstyles();
}
The problem is, QFrame inherits from QWidget, and if it has no parent, it is going to create a window.
From QWidget:details section :
Every widget's constructor accepts one or two standard arguments:
- QWidget *parent = 0 is the parent of the new widget. If it is 0 (the default), the new widget will be a window. If not, it will be a child of parent, and be constrained by parent's geometry (unless you specify Qt::Window as window flag).
To fix your specific case, create the QFrame object with the parent :
frame = new QFrame(this);
You can not set layout of a QMainWindow
(or simple subclass), you can only set it's central widget. I assume your MainWindow
is a subclass of QMainWindow
. But you can of course set layout to that central widget, so you can do this:
MainWindow::MainWindow() // parent will be nullptr, so this will be a window
{
showMaximized();
// create and set central widget
QWidget *cw = new QWidget();
setCentralWidget(cw); // will set cw's parent
// Note: there's no need to make cw a member variable, because
// MainWindow::centralWidget() gives direct access to it
frame = new QFrame();
layout = new QHBoxLayout();
button = new QPushButton("Push"); // this is not used at all? why is it here?
layout->addWidget(frame);
//frame->show(); // not needed, child widgets are shown automatically
cw->setLayout(layout); // will set parent of all items in the layout
Setstyles();
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.