I try to build a frameless window with a single text label with changing text depending on chosen language and a boarder around it. This window should always have the smallest possible size. Here's the simple code without any configurations I tried so far.
QMainWindow* clientIDDisplay = new QMainWindow(0, Qt::Window
| Qt::FramelessWindowHint
| Qt::WindowStaysOnTopHint);
QGroupBox* mainWidget = new QGroupBox(clientIDDisplay);
mainWidget->setStyleSheet(stylesheetGroupBox);
QLabel* labelClientID = new QLabel(clientIDDisplay);
labelClientID->setStyleSheet(stylesheetLabel);
labelClientID->setText("Client");
QHBoxLayout* mainLayout = new QHBoxLayout(clientIDDisplay);
mainLayout->addWidget(labelClientID);
mainWidget->setLayout(mainLayout);
clientIDDisplay->setCentralWidget(mainWidget);
clientIDDisplay->show();
This shows the window but it's not as small as it should be, ther's much space left.
Using setMinimumSize(0,0)
doesn't help.
I think I understand to use QSizePolicy
to resize widgets depending on each other in one layout, as explained in this post layout mechanism. But it's a single widget in a groupbox, don't know whitch widget causes the bigger size of this window.
Using setFixedSize()
, I'm able to get a smaller size, but I don't know a way to set the right size. width()
of the label is NOT the width of the shown text.
Can anyone please explain which configurations I have to set to get my minimalistic window? I'm sure I overlook something, but I'm stuck.
First, You need to adjust the size of each widget to fit to its content.
labelClientID->adjustSize();
mainWidget->adjustSize();
clientIDDisplay->adjustSize();
It need to be done bottom up to work as expected. The lowest level widget first, then its parent, etc.. up to the top level widget. It should work with default size policies and size constraints.
In your case do it before clientIDDisplay->show();
to prevent flicker on the screen.
In your code you are creating layout and widget with the wrong parents. fix that.
Second, you don't need a QMainwindow
as top parent, a QWidget
give a better result.
Try it for yourself:
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QWidget* top_widget = new QWidget(0, Qt::Widget | Qt::FramelessWindowHint
| Qt::WindowStaysOnTopHint);
QGroupBox* mainWidget = new QGroupBox(top_widget);
QLabel* labelClientID = new QLabel();
labelClientID->setText("Client");
QHBoxLayout* mainLayout = new QHBoxLayout(mainWidget);
mainLayout->addWidget(labelClientID);
mainWidget->setLayout(mainLayout);
labelClientID->adjustSize();
mainWidget->adjustSize();
top_widget->adjustSize();
top_widget->show();
return a.exec();
}
Widget:
Window (just changing the type of top_widget
and using Qt::Window
):