Search code examples
qtgrid

Set grid spacing using Qt


I have created a Gird with QPushButton. I would like to set each button spacing to 0. As you can see I set it, but there is still little padding around the button, and I would like to eliminate it.

QVector<QVector<QPushButton*>> buttons(10);

void MainWindow::createGrid() {
    QFrame *frame = new QFrame(this);
    QGridLayout *layout = new QGridLayout(frame);

    layout->setMargin(0);
    layout->setSpacing(0);

    for(int i = 0; i < 10; ++i){
        buttons[i].resize(10);

        for(int j = 0; j < 10; ++j){
            QPushButton *button = new QPushButton("0");
            button->setMinimumSize(50,50);
            button->setMaximumSize(50,50);

            layout->addWidget(button,i,j);

            buttons[i][j] = button;
        }
    }

    setCentralWidget(frame);  

}

enter image description here


Solution

  • Actually you already have proper settings, spacing is correct parameter for you task.

    The issue here is that you QStyle (looks like you are using Windows and your default style is QWindowsVistaStyle). That style just draws QPushButton in this way, without Bevels (more info about button structure: https://doc.qt.io/qt-5/style-reference.html#push-buttons).

    To ensure that it is your issue - you can setup custom style in QtDesigner and check application preview with another style:

    Settings->Preferences->Forms->Print/Preview Configuration->Style enter image description here

    With Fusion style it will looks like this: enter image description here

    To set custom style from code you need to add something like this:

    QApplication app(argc, argv);
    app.setStyle(QStyleFactory::create("Fusion"));