Laxynium Laxynium - 1 month ago 8
C++ Question

changing number of QPushButton

I'm new in Qt. I have got Class TicTacToeWidget which stores QList with QPushButton.

int m_size is initialized with 3 and works fine and i see 3x3 board, but when i try to change m_size in main.cpp to other value nothing happends. I can't find out why it doesn't work.

#ifndef TICTACTOEWIDGET_H
#define TICTACTOEWIDGET_H

#include <QWidget>
class QPushButton;
class TicTacToeWidget : public QWidget
{
Q_OBJECT

public:
TicTacToeWidget(QWidget *parent = 0);
~TicTacToeWidget();
int size()const;
void resizeBoard(int m);
private:
QList<QPushButton *> m_board;
int m_size;
void setupBoard(int m);
void clearBoard();


};

#endif // TICTACTOEWIDGET_H


And implementation

#include "tictactoewidget.h"
#include <QMessageBox>
#include <QGridLayout>
#include <QPushButton>
#include <QDebug>
TicTacToeWidget::TicTacToeWidget(QWidget *parent)
: QWidget(parent),m_size(3)
{
setupBoard(3);
}

TicTacToeWidget::~TicTacToeWidget()
{

}

int TicTacToeWidget::size() const
{
return m_size;
}

void TicTacToeWidget::resizeBoard(int m)
{
setupBoard(m);
}

void TicTacToeWidget::setupBoard(int m)
{

QGridLayout *gridLayout= new QGridLayout;
m_size=m;
m_board.clear();
for(int i=0;i<m_size;i++)
{
for(int j=0;j<m_size;j++)
{
QPushButton *button= new QPushButton;
button->setSizePolicy(QSizePolicy::Minimum,QSizePolicy::Minimum);
button->setText(" ");
gridLayout->addWidget(button,i,j);
}
}
setLayout(gridLayout);

}

void TicTacToeWidget::clearBoard()
{
for(auto &it:m_board)
{
this->layout()->removeWidget(it);
}
m_board.clear();

}


And main

#include "tictactoewidget.h"
#include <QApplication>
using namespace std;
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
TicTacToeWidget w;
w.resizeBoard(5);
w.show();

return a.exec();
}

Answer

http://doc.qt.io/qt-4.8/qwidget.html#setLayout

If there already is a layout manager installed on this widget, QWidget won't let you install another. You must first delete the existing layout manager

Comments