本文介绍了QLabel 不显示在 QWidget 中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 Qt 应用程序中有以下层次结构:QMainWindow > QWidget (centralWidget) > QWidget (subclassed) > QLabel

I have the following hierarchy in my Qt Application:QMainWindow > QWidget (centralWidget) > QWidget (subclassed) > QLabel

我的 QMainWindow 代码中的初始化代码:

Initialization code in my QMainWindow code:

centralWidget = new QWidget();
centralWidget->setGeometry(0,0,width,height);
chatWidget=new ChatWidget(this); // the subclassed QWidget
setCentralWidget(centralWidget);

在我的子类 QWidget 初始化(与 Qt App 初始化同时发生)中,我有以下代码:

In my subclassed QWidget initialization (which happens at the same time than the Qt App initialization) I have the following code:

ChatWidget::ChatWidget(QWidget *parent):QWidget(parent)
{
    QLabel  *lbl;
    lbl=new QLabel(this);
    lbl->setText("Hello World 1"); <-- Is properly Display
}

void ChatWidget::displayChatAfterButtonPressed()
{
    QLabel *lbl;
    lbl=new QLabel(this);
    lbl->setText("Hello World 2"); <-- Does NOT appear
}

当从类初始化中添加 QLabel 时,消息会很好地显示在小部件中.

When the QLabel is added from the class initialization then the message is well displayed in the widget.

但是,当我按下按钮后启动相同的代码(通过同一 QWidget 子类中的函数)时,文本不会出现在屏幕上.

我不想使用布局,因为我需要准确定位我的标签.

试图重新粉刷,但也无济于事.

初始化完成后如何正确动态地显示标签?

However when I launch the same code after a button pressed (via a function in the same QWidget subclass), then the text does not appear on screen.

I don't want to use layouts as I need to exactly position my labels.

Tried to repaint, but didn't help neither.

How can I properly and dynamically display a label after the initialization is done ?

推荐答案

小部件第一次可见时调用对其子项可见,但由于您是在之后创建它,因此它们可能不会调用该方法,可能的解决方案是调用 show 方法.

Widgets when they are visible for the first time call to be visible to their children, but since you are creating it afterwards they probably are not calling that method, a possible solution is to call the show method.

void ChatWidget::displayChatAfterButtonPressed()
{
    QLabel *lbl;
    lbl=new QLabel(this);
    lbl->setText("Hello World 2");
    lbl->show();
}

评论: QMainWindow 你设置了一个中央小部件,然后创建 chatWidget 作为 QMainWindow 的父级,我觉得很奇怪,一般不建议在 QMainWindow 中添加子级,因为它有一个给定的结构,应该做的是把它放在centralwidget里面.

comment: it seems strange to me that the QMainWindow you set a central widget and then create the chatWidget as a parent to the QMainWindow, it is generally not recommended to add children to the QMainWindow because it has a given structure, what should be done is to place it inside the centralwidget.

这篇关于QLabel 不显示在 QWidget 中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-26 15:04