Question

I'm started studying QT. When I create a MainWindow and placing some widgets on it in ane layout, there is a gap between edge of window and widgets, like that:

enter image description here

How can I switch off this gaps?

layout()->setContentsMargins(0,0,0,0); and editing stylesheets of window, but there was no effect. What should I do?

Was it helpful?

Solution

A QMainWindow is slightly different than a QDialog or QWidget in that it has the concept of a "central widget". The window has predefined areas to handle stuff like toolbars and menus and docks, and defines the central widget as the main content for the window. The window itself is not usually assigned a layout. But what I assume you are doing is setting the values on the windows layout (which will not have an effect).

The widget you set as the central widget will most likely have its own layout. By default the central widget can expand to the edges already. Consider this example first:

#include <QApplication>
#include <QMainWindow>
#include <QVBoxLayout>
#include <QListWidget>

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

    QMainWindow *window = new QMainWindow;
    window->resize(800,600);

    QListWidget *listWidget = new QListWidget;
    window->setCentralWidget(listWidget);

    window->show();

    return a.exec();
}

You will see the list widget fully expanded to the edges. But in a more realistic example:

#include <QApplication>
#include <QMainWindow>
#include <QVBoxLayout>
#include <QListWidget>

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

    QMainWindow *window = new QMainWindow;
    window->resize(800,600);

    QWidget *central = new QWidget;
    QListWidget *listWidget = new QListWidget;

    QVBoxLayout *layout = new QVBoxLayout;
    layout->addWidget(listWidget);

    //Uncomment this following line to remove margins
    //layout->setContentsMargins(0,0,0,0);

    central->setLayout(layout);

    window->setCentralWidget(central);

    window->show();

    return a.exec();
}

You have a container widget, which is then composed with a layout, and the list widget. The layout of this central widget is the one that introduces the margins.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top