Dynamically creating a vector of push buttons to a grid layout in Qt C++
-
Complete beginner at Qt, so bear with me.
I am attempting to create a grid of push buttons similar to a tic tac toe board, but the size will be variable. I've used some tactics found here and on the web but am at a loss at creating it dynamically. I am not having issues outside of creating something dynamically. I'd appreciate any tips or suggestions.Code was derived from https://github.com/aosama16/Qt-Tic-Tac-Toe in an attempt of understanding.
struct Cell { QPushButton *cellBtn = nullptr; int row = defaults::INVALID_CELL; int col = defaults::INVALID_CELL; Cell(QPushButton *cellBtn, int row, int col) : cellBtn(cellBtn), row(row), col(col) {} }; void SOSGame::on_StartButton_clicked() { int size = ui->BoardSizeSlider->value(); buildCellButtons(size); /*QMessageBox msg; msg.setText();*/ } std::vector<Cell> SOSGame::buildCellButtons(int boardSize) { std::vector<Cell> cells; cells.reserve(boardSize * boardSize); for (size_t row = 0; row < boardSize; ++row) { for (size_t col = 0; col < boardSize; ++col) { // Add buttons to gridLayout QPushButton *btn = new QPushButton(); btn->setProperty("cell", true); ui->GameBoard->addWidget(btn, static_cast<int>(row), static_cast<int>(col), defaults::GUI_CELL_ROW_SPAN, defaults::GUI_CELL_COLUMN_SPAN); // Reference to cells cells.emplace_back(btn, row, col); } } // Adjusts window size to fit children widgets added dynamically adjustSize(); // Return by value to allow for RVO (Copy Ellision) return cells; }
-
What's
ui
andadjustSize()
? -
Hi and welcome to devnet,
If you want a two dimensional board, then you need a two dimensional container. For example a vector of vector. That way you have the dynamic in both dimensions.
-
@SGaist said in Dynamically creating a vector of push buttons to a grid layout in Qt C++:
Hi and welcome to devnet,
If you want a two dimensional board, then you need a two dimensional container. For example a vector of vector. That way you have the dynamic in both dimensions.
Or just a vector with rows*cols items. Then your row, col access becomes vector[row * cols + col]
Single contiguous memory chunk vs. multiple.
-
Hi, thanks for your reply. ui->GameBoard was the QGridLayout created in Qt designer.
It turns out that adjustsize() did absolutely nothing. lol.I was able to get it working, however now I'm in the process of getting connections on click.
-
@SGaist
Hi and thank you!I originally started with a vector of vectors, and thought that it might have been the problem. I may go back to that thought, thank you. I was able to get it working, but now working on how to add connections/edit text on these buttons after the fact. I appreciate the advice. I'm thinking of trying to use a QTableWidget instead.
-
You can simply iterate your vector and then do the connections you want on the current object in the iteration loop.
-