如何获取QLabel扩展到全宽? [英] How do I get a QLabel to expand to full width?

查看:1060
本文介绍了如何获取QLabel扩展到全宽?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要一个 QLabel 展开到容器的整个宽度,无论内容如何。 (我想这是因为我动态设置文本和添加小部件,以后它导致它切断部分文本)

I want a QLabel to expand to full width of the container regardless of the contents. (I want this because I dynamically set the text and add widgets later which cause it to cut off part of the text)

Widget::Widget(QWidget *parent)
    : QWidget(parent)
{
    this->setFixedSize(100,100);
    QHBoxLayout *layout = new QHBoxLayout;
    this->setLayout(layout);
    QLabel *label = new QLabel;
    label->setStyleSheet("background-color:blue");
    label->setSizePolicy(QSizePolicy::MinimumExpanding, 
                         QSizePolicy::MinimumExpanding);
    label->setText(tr("test"));
    layout->addWidget(label, 0, Qt::AlignTop | Qt::AlignLeft);
}

此代码显示蓝色框不会展开到整个宽度,为什么?

This code shows that the blue box does not expand to the entire width, why?

推荐答案

您必须设置:

layout->setContentsMargins(0,0,0,0);

默认情况下,每个QWidget或QFrame在每个方向添加15像素的边距。

By default every QWidget or QFrame add 15 pixels of margin in every direction.

主要的问题是当你添加小部件到布局时设置对齐。改用 label-> setAlignment

The main problem is with setting the alignment when you add the widget to the layout. Use label->setAlignment instead.

layout->addWidget(label);

我编译了您的代码,它适用于这些更改。

I compiled your code, it works with those changes.

这是最小的例子:

#include <QApplication>
#include <QtGui>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    QWidget* w = new QWidget;
    w->setFixedSize(100,100);
    QHBoxLayout* layout = new QHBoxLayout;
    layout->setContentsMargins(0,0,0,0);
    w->setLayout(layout);
    QLabel* label = new QLabel;
    label->setAlignment(Qt::AlignTop | Qt::AlignLeft);
    label->setContentsMargins(0,0,0,0);
    label->setStyleSheet("background-color:blue");
    label->setSizePolicy(QSizePolicy::MinimumExpanding,
                     QSizePolicy::MinimumExpanding);
    label->setText("test");
    layout->addWidget(label);
    w->show();
    return a.exec();
}

这篇关于如何获取QLabel扩展到全宽?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆