简体   繁体   English

Qt 设置 QWidget 的默认宽度

[英]Qt set default width of a QWidget

One of those days when you get stuck on something stupid.当你被一些愚蠢的事情卡住的那些日子之一。 I've got the Min/Max width set, but it defaults to the Max width.我设置了最小/最大宽度,但默认为最大宽度。 I want it to default to the minimum width.我希望它默认为最小宽度。 How do I do this.我该怎么做。

I also had massive trouble understanding why there isn't a "set to this size, but don't fix the values" method.我也很难理解为什么没有“设置为这个大小,但不修复值”的方法。 It's called resize, like this:它被称为调整大小,如下所示:

QWidget *widget= new QWidget();
label->resize(50,50);

Consider the following code考虑以下代码

QLabel *label = new QLabel();
label->setMinimumSize(50,50);
label->setMaximumSize(100,100);
label->setText("Hello World");
label->show();

Here label will be displayed with the size 50:50(width:height) and we can enlarge it to maximum 100:100(width:height).这里标签将显示为 50:50(width:height) 大小,我们可以将其放大到最大 100:100(width:height)。 Here MinumumSize is given as 50:50 and MaximumSize is given as 100:100.这里 MinumumSize 为 50:50,MaximumSize 为 100:100。

You can set the default minimum width/height like this:您可以像这样设置默认的最小宽度/高度:

int width = 100;
int height = 100;
QWidget * widget = new QWidget();
widget->setMinimumSize(width, height);
widget->deleteLater();

See more about setMinimumSize here: http://qt-project.org/doc/qt-4.8/qwidget.html#minimumSize-prop在此处查看有关 setMinimumSize 的更多信息: http : //qt-project.org/doc/qt-4.8/qwidget.html#minimumSize-prop

Is your widget in a layout ?您的小部件是否在布局中? You can try to change the size policy:您可以尝试更改大小策略:

widget->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum);

Getting the default size of a widget can be done using:可以使用以下方法获取小部件的默认大小:

QWidget widget(this);
widget.minimumSizeHint()

it returns the minimum size, the widget wants to have to be able to display the content.它返回最小尺寸,小部件希望能够显示内容。

Eg:例如:

QSpinBox aSpinBox(this);
const QSize defaultSizeSpinBox = aSpinBox.minimumSizeHint();
std::cout << defaultSizeSpinBox.width() << std::endl;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM