Reputation: 1021
I tried to build a simple GUI application. Then I got those warnings:
QLayout: Attempting to add QLayout "" to MainWindow "", which already has a layout
QWidget::setLayout: Attempting to set QLayout "" on MainWindow "", which already has a layout
I googled that you have to set central widget in MainWindow
. And here is my implement which is still not working:
.h
class MainWindow : public QMainWindow
{
Q_OBJECT
QWidget *centralWidget;
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
void setButtons();
...
private:
Ui::MainWindow *ui;
QPushButton *btn[9][9];
}
.cpp
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
centralWidget = new QWidget(this);
this->setCentralWidget(centralWidget);
...
}
void MainWindow::setButtons()
{
for(int i = 0; i < 9; i++) {
for(int j = 0; j < 9; j++) {
btn[i][j] = new QPushButton(this);
...
QVBoxLayout *vLayout = new QVBoxLayout(this);
vLayout->addWidget(btn[i][j]);
centralWidget->setLayout(vLayout);
}
}
}
After trying this, I still received the warning messages, how can I solve this problem?
Thanks.
Upvotes: 0
Views: 614
Reputation: 12879
Your code has two basic issues. Firstly, the statement...
QVBoxLayout *vLayout = new QVBoxLayout(this);
will instantiate a new QVBoxLayout
with this
as its parent. Since this
is of type MainWindow *
and MainWindow
inherits from QMainWindow
you are effectively calling QMainWindow::setLayout
-- that's the source of the error message...
QLayout: Attempting to add QLayout "" to MainWindow "", which already has a layout
Secondly, you're creating a new QVBoxLayout
on each loop iteration. If you really do want the buttons vertically aligned in a layout try something like...
void MainWindow::setButtons ()
{
QVBoxLayout *vLayout = new QVBoxLayout(centralWidget);
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
btn[i][j] = new QPushButton;
...
vLayout->addWidget(btn[i][j]);
}
}
}
Upvotes: 2