QLabels have same width regardless of text?
-
So I have a
QHBoxLayout
that gets filled with instances of a subclass ofQLabel
. I want the spaces between one label's text and the next to all be the same, so I wrap theQHBoxLayout
in a widget and try to limit that widget's width to a sum of each label's widths which was calculated when the labels were constructed prior to being added to any layout://instantiate the labels int fullWidth = 0; for(auto& word : words) { auto label = new WordListLabel(word, this); fullWidth += label->width(); wordListHBox->addWidget(label); } //wrap the layout in a widget auto wordListWidget = new QWidget(this); wordListWidget->setLayout(wordListHBox); wordListWidget->setMaximumWidth(fullWidth);
Stepping through this in the debugger I found that every label, regardless of its text, is being instantiated with a width of 100. Is there some setting I have to adjust to get the labels to be sized based on the length of their text? Or is this just the wrong way to go about evenly spacing text in a
QHBoxLayout
? Any insight much appreciated. -
You should try sizeHint() - since the widget is not shown yet, the width is a default value.
-
You can't set a sizeHint()... you should use it.