PDA

View Full Version : QLayout and QMainWindow



Cat
19th October 2015, 11:59
Hello. I recently started to work with Qt and Qwt. I can't find my mistake by myself. Please help me. There is the code:
I know that my mistakes in somewhere here:

.h file


...
class MainWindow : public
QMainWindow
{
Q_OBJECT
QWidget *centralWidget;
public:
MainWindow(QWidget *parent = 0);
...

.cpp



MainWindow::MainWindow(QWidget *parent):
QMainWindow(parent) {
...
...
void MainWindow::setPlotButton() {
button = new QPushButton("push"),
button->setCheckable(true);

connect(button, SIGNAL(toggled(bool)), this, SLOT(toggled(bool)));

QHBoxLayout *plotsLayout = new QHBoxLayout;
plotsLayout->setSpacing(10);
plotsLayout->addWidget(funPlot);

QHBoxLayout *buttonsLayout = new QHBoxLayout ;
buttonsLayout->addWidget(button);

QVBoxLayout *widgetLayout = new QVBoxLayout;
widgetLayout->addLayout(plotsLayout);
widgetLayout->addLayout(buttonsLayout);

setLayout(widgetLayout);
...
}

I recieve a message "QWidget::setLayout: Attempting to set QLayout "" on MainWindow "", which already has a layout". What I should change?

weiweiqiao
19th October 2015, 13:38
Use setCentralWidget function to add centralWidget.




---sory about bad english.

Cat
19th October 2015, 15:27
Do you mean to use setCentralWidget() instead of setLayout(widgetLayout)?

Cat
20th October 2015, 17:08
Please, can you explain it in more detail?

yeye_olive
21st October 2015, 10:01
This is not how QMainWindow is meant to be used. You need to put all the widgets inside a "container" widget, and set this container as the QMainWindow's central widget. For instance:


QWidget *centralWidget = new QWidget(this /* the main window */);
QVBoxLayout *widgetLayout = new QVBoxLayout(centralWidget);
QHBoxLayout *buttonsLayout = new QHBoxLayout;
button = new QPushButton("push", centralWidget);
buttonsLayout->addWidget(button);
widgetLayout->addLayout(buttonsLayout);
// ...
setCentralWidget(centralWidget);

IMHO Qt's API for managing layouts, widgets, containment and ownership is messy and counter-intuitive. Whenever I need to do this by hand, I just do a mock up with Designer and have a look at the generated code.

weiweiqiao
21st October 2015, 14:20
yes, setCentralWideget() add widget in mainwindow; setLayout add layout for mainwindow. they are different.

--sory about bad english.