Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Qt - setLayout() and setCentralWidget()

Tags:

qt

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". I found that I have to use a function setCentralWidget(), but what exactly I should change?

like image 805
Kate Avatar asked Jul 29 '26 13:07

Kate


1 Answers

Instead of just calling setLayout(widgetLayout); which would call the MainWindow method, try calling:

centralWidget()->setLayout(widgetLayout);

The mainwindow itself already owns a layout with the centralwidget, a QMenuBar, QStatusBar and QAction-Bar.

You want your new widgets to reside in the central widget, often also named as "content Widget".

like image 162
Sebastian Lange Avatar answered Aug 05 '26 00:08

Sebastian Lange



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!