Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.6k views
in Technique[技术] by (71.8m points)

qt - QLabel does not display in QWidget

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

Initialization code in my QMainWindow code:

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

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
}

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

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 ?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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();
}

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...