gpt4 book ai didi

c++ - QLabel 占用完整空间

转载 作者:行者123 更新时间:2023-11-28 07:27:16 25 4
gpt4 key购买 nike

我有一个 QWidget,其中包含一个 QVBoxLayout,该布局包含一个 QLabel 和 QToolButtons。我的问题是,QLabel 占用了所有空间。我找到的唯一解决方案是将 maximumHeight 设置为 QLabel,但如果我这样做,Qt::AlignTop 将不再起作用。

主要.cpp:

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

QWidget window_main;

QWidget *widget_steps = new QWidget(&window_main);
widget_steps->setFixedWidth(75);
widget_steps->move(QPoint(0, 0));
widget_steps->setStyleSheet("background-color: red;");

QVBoxLayout *layout_steps = new QVBoxLayout(widget_steps);
layout_steps->setContentsMargins(0, 0, 0, 0);
layout_steps->setSpacing(0);

QLabel *label_steps_start = new QLabel("steps:");
label_steps_start->setAlignment(Qt::AlignHCenter | Qt::AlignTop);
label_steps_start->setStyleSheet("background-color: blue;");
layout_steps->addWidget(label_steps_start);

QToolButton *tbutton_step1 = new QToolButton();
layout_steps->addWidget(tbutton_step1);

QToolButton *tbutton_step2 = new QToolButton();
layout_steps->addWidget(tbutton_step2);

QToolButton *tbutton_step3 = new QToolButton();
layout_steps->addWidget(tbutton_step3);


window_main.showMaximized();

return a.exec();
}

这是一张图片,显示了 QLable 占用了多少空间(蓝色空间): QLabel_space

所以请帮助最小化 QLable 占用的空间:)

最佳答案

您的问题是工具按钮具有固定大小,因此在调整大小时,标签是唯一可以增长的类型:因此:添加标签后,在布局中添加拉伸(stretch):

layout_steps->addWidget(label_steps_start);
layout_steps->addStretch();

修改后的代码 - 在底部添加拉伸(stretch)。标签大小保持不变,按钮保留在其下方。为了测试,我已经移除了外面的整个主窗口。

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

QWidget *widget_steps = new QWidget;
widget_steps->setFixedWidth(75);
widget_steps->move(QPoint(0, 0));
widget_steps->setStyleSheet("background-color: red;");

QVBoxLayout *layout_steps = new QVBoxLayout(widget_steps);
layout_steps->setContentsMargins(0, 0, 0, 0);
layout_steps->setSpacing(0);

QLabel *label_steps_start = new QLabel("steps:");
label_steps_start->setAlignment(Qt::AlignHCenter | Qt::AlignTop);
label_steps_start->setStyleSheet("background-color: blue;");
layout_steps->addWidget(label_steps_start);
//--- Removed.... layout_steps->addStretch();

QToolButton *tbutton_step1 = new QToolButton();
layout_steps->addWidget(tbutton_step1);

QToolButton *tbutton_step2 = new QToolButton();
layout_steps->addWidget(tbutton_step2);

QToolButton *tbutton_step3 = new QToolButton();
layout_steps->addWidget(tbutton_step3);
layout_steps->addStretch(); //<----- Added!
widget_steps->show();

return a.exec();
}

关于c++ - QLabel 占用完整空间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18541345/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com