Qt - setLayout() and setCentralWidget()

6

我最近开始使用Qt和Qwt。我自己找不到错误,请帮助我。这是代码。 我知道我的错误在这里的某个地方:

.h文件

  ...

  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);
  ...
  }

我收到了一条消息:"QWidget::setLayout: Attempting to set QLayout "" on MainWindow "", which already has a layout"。我发现我需要使用一个函数setCentralWidget(),但我应该改变什么呢?

2个回答

9

不要只调用setLayout(widgetLayout);这个方法,因为它会调用MainWindow中的方法。尝试改为调用:

centralWidget()->setLayout(widgetLayout);

主窗口本身已拥有一个布局,其中包含 centralwidget, QMenuBar, QStatusBarQAction-Bar。

你希望你的新小部件驻留在中央小部件中,通常也称为“内容小部件”。


同样适用于停靠窗口部件。 - Keshav Sahu

0
你已经实例化了QWidget,这是正确的方向,但你需要使用setcentralWidget()函数将你命名为centralWidget的QWidget对象设置为中心窗口部件。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接