C++ 将 QLabel 添加到 QWidget

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26300293/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 11:33:53  来源:igfitidea点击:

Adding a QLabel to a QWidget

c++qtqwidgetqlabelqlayout

提问by Sadaab

I am new to Qt and C++ and working on an application and I am trying to add QLabelin a QWidget, using QHBoxLayout. I am setting the text of label to something but it is not visible in the Label.

我是新来的Qt和C ++中的应用程序工作,我想补充QLabel一个QWidget,使用QHBoxLayout。我正在将标签文本设置为某些内容,但它在标签中不可见。

Here is the piece of the code:

这是代码的一部分:

setStyleSheet( "QWidget{ background-color : rgba( 160, 160, 160, 255); border-radius : 7px;  }" );
QLabel *label = new QLabel(this);
QHBoxLayout *layout = new QHBoxLayout();
label->setText("Random String");
layout->addWidget(label);
setLayout(layout);    

The styleSheet is for the Widget in which QLabel is added.

styleSheet 用于添加 QLabel 的 Widget。

The string "Random String"doesn't get displayed inside the label.

字符串"Random String"不会显示在标签内。

Please help.

请帮忙。

回答by Iuliu

Your code has a typo, it's QLabel, notQLable...

你的代码有一个错字,它是QLabel不是QLable......

Assuming that this would notify you at compile time I don't see what is the problem with the code, maybe you could share more of your project with us...

假设这会在编译时通知您,我看不出代码有什么问题,也许您可​​以与我们分享更多您的项目...

I did a small test of this class:

我对这门课做了一个小测试:

mynewwidget.h

mynewwidget.h

#ifndef MYNEWWIDGET_H
#define MYNEWWIDGET_H

#include <QWidget>

class MyNewWidget : public QWidget
{
    Q_OBJECT
public:
    explicit MyNewWidget(QWidget *parent = 0);
};

#endif // MYNEWWIDGET_H

mynewwidget.cpp

mynewwidget.cpp

#include "mynewwidget.h"

#include <QHBoxLayout>
#include <QLabel>

MyNewWidget::MyNewWidget(QWidget *parent) :
    QWidget(parent)
{
    setStyleSheet( "QWidget{ background-color : rgba( 160, 160, 160, 255); border-radius : 7px;  }" );
    QLabel *label = new QLabel(this);
    QHBoxLayout *layout = new QHBoxLayout();
    label->setText("Random String");
    layout->addWidget(label);
    setLayout(layout);
}

And the result is

结果是

http://i.imgur.com/G6OMHZX.png

http://i.imgur.com/G6OMHZX.png

which I assume it's what you want...

我认为这是你想要的......