Project

General

Profile

RE: WGridLayout issue (again) ยป qgridlayout.cpp

Qt GridLayout example - David Gaarenstroom, 05/02/2013 04:42 PM

 
#include <QApplication>
#include <QGridLayout>
#include <QLabel>
#include <QLineEdit>
#include <QMainWindow>
#include <QPalette>

const int COL_SIZE = 10;
const int ROW_SIZE = 20;

void CreateGrid(QMainWindow* mainWindow)
{
int columnCount = 12;
int rowCount = 5;
mainWindow->setWindowTitle("Test Grid");
// resizing mainWindow to at most its desired size (
mainWindow->resize(columnCount * COL_SIZE, rowCount * ROW_SIZE);

QWidget* container = new QWidget(mainWindow);
container->resize(columnCount * COL_SIZE, rowCount * ROW_SIZE);
QGridLayout* gridLayout = new QGridLayout(container);

gridLayout->setHorizontalSpacing(0);
gridLayout->setVerticalSpacing(0);

for (int c = 0; c < columnCount; ++c) {
gridLayout->setColumnMinimumWidth(c, COL_SIZE);
gridLayout->setColumnStretch(c, 0);
}
for (int r = 0; r < rowCount; ++r) {
gridLayout->setRowMinimumHeight(r, ROW_SIZE);
gridLayout->setRowStretch(r, 0);
}

// Add an outer row/column that can resize freely
gridLayout->setColumnMinimumWidth(columnCount, 0);
gridLayout->setColumnStretch(columnCount, 1);
gridLayout->setRowMinimumHeight(rowCount, 0);
gridLayout->setRowStretch(rowCount, 1);

QPalette odd, even;
odd.setColor(QPalette::Background, Qt::black);
even.setColor(QPalette::Background, Qt::white);

for (int c = 0; c < columnCount; ++c) {
QWidget* square = new QWidget(container);
square->setAutoFillBackground(true);
square->setPalette((c + rowCount - 1) % 2 ? odd : even);
gridLayout->addWidget(square, rowCount - 1, c);
}
for (int r = 0; r < rowCount; ++r) {
QWidget* square = new QWidget(container);
square->setAutoFillBackground(true);
square->setPalette((columnCount - 1 + r) % 2 ? odd : even);
gridLayout->addWidget(square, r, columnCount - 1);
}

QLabel* field1 = new QLabel("somelabel", container);
gridLayout->addWidget(field1, 0, 3, 1, 5);
QLabel* field2 = new QLabel("label", container);
gridLayout->addWidget(field2, 1, 0, 1, 3);
QLineEdit* field3 = new QLineEdit("somelabel", container);
gridLayout->addWidget(field3, 1, 4, 1, 6);
QLabel* field4 = new QLabel("label", container);
gridLayout->addWidget(field4, 2, 0, 1, 3);

QPalette palette1;
palette1.setColor(QPalette::Background, Qt::yellow);
field1->setAutoFillBackground(true);
field1->setPalette(palette1);
QPalette palette2;
palette2.setColor(QPalette::Background, Qt::red);
field2->setAutoFillBackground(true);
field2->setPalette(palette2);
QPalette palette3;
palette3.setColor(QPalette::Background, Qt::blue);
field3->setAutoFillBackground(true);
field3->setPalette(palette3);
QPalette palette4;
palette4.setColor(QPalette::Background, Qt::green);
field4->setAutoFillBackground(true);
field4->setPalette(palette4);

mainWindow->setCentralWidget(container);
}

int main(int argc, char** argv)
{
QApplication a(argc, argv);

QMainWindow mainWindow;

CreateGrid(&mainWindow);
mainWindow.show();

return a.exec();
}
    (1-1/1)