c++ - QLabel 占用完整空间

标签 c++ qt space qlabel

我有一个 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/

相关文章:

c++ - 设置一个 2d char 空格数组

c++ - QNetworkRequest导致程序到 "finish unexpectedly"

qt - CMake QT LIBRARIES 二进制等效项

c - sscanf 没有来自标准输入的工作空间

mysql - 当字符串包含空格时应用程序不更新数据库

haskell - 修复一个特别模糊的 Haskell 空间泄漏

c++ - 通过向右移动对值数组进行排序

c++ - 拾色轮

C++ 时间库和 Octave .oct 文件

Qt unicode 和元音变音