Qt QLabel不显示在QWidget中
我的Qt应用程序中有以下层次结构: QMainWindow>QWidget(centralWidget)>QWidget(子类)>QLabel 我的QMainWindow代码中的初始化代码:Qt QLabel不显示在QWidget中,qt,qwidget,qlabel,Qt,Qwidget,Qlabel,我的Qt应用程序中有以下层次结构: QMainWindow>QWidget(centralWidget)>QWidget(子类)>QLabel 我的QMainWindow代码中的初始化代码: centralWidget = new QWidget(); centralWidget->setGeometry(0,0,width,height); chatWidget=new ChatWidget(this); // the subclassed QWidget setCentralWidge
centralWidget = new QWidget();
centralWidget->setGeometry(0,0,width,height);
chatWidget=new ChatWidget(this); // the subclassed QWidget
setCentralWidget(centralWidget);
在我的子类QWidget初始化(与Qt应用程序初始化同时发生)中,我有以下代码:
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
}
ChatWidget::ChatWidget(QWidget*parent):QWidget(parent)
{
QLabel*lbl;
lbl=新的QLabel(本);
lbl->setText(“Hello World 1”);setText(“Hello World 2”);小部件第一次可见时调用对其子部件可见,但由于您在创建它之后,它们可能不会调用该方法,因此一种可能的解决方案是调用show方法
void ChatWidget::displayChatAfterButtonPressed()
{
QLabel *lbl;
lbl=new QLabel(this);
lbl->setText("Hello World 2");
lbl->show();
}
注释:我觉得很奇怪,QMainWindow设置了一个中心小部件,然后创建了chatWidget作为QMainWindow的父窗口,通常不建议向QMainWindow添加子窗口,因为它具有给定的结构,应该做的是将其放置在中心widget中。我们需要显示由创建的标签按钮单击,因为已绘制centralwidget。 这里是一个工作示例,我添加了这个作为答案,我还注意到最好将
chatWidget
作为子项添加到centralWidget
中,在原始代码中,它添加到了UI中。这是您的选择
主窗口:
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
//
ui->setupUi(this);
centralWidget = new QWidget();
centralWidget->setGeometry(width,height);
chatWidget=new ChatWidget(centralWidget); // the subclassed QWidget
setCentralWidget(centralWidget);
// added testing
QPushButton *btn = new QPushButton("MyButton",centralWidget);
btn->setGeometry(100,100,100,100);
btn->setMaximumSize(100,100);
connect(btn,&QPushButton::clicked, chatWidget, &ChatWidget::displayChatAfterButtonPressed);
}
和聊天工具:
ChatWidget::ChatWidget(QWidget *parent):QWidget(parent)
{
QLabel *lbl;
lbl=new QLabel(this);
lbl->setText("Hello World 1");
}
void ChatWidget::displayChatAfterButtonPressed()
{
QLabel *lbl;
lbl=new QLabel(this);
lbl->setText("Hello World 2");
lbl->show();
}
在发布之前,我没有看到你的答案!无论如何,我之前已经发表了评论,但后来意识到建议进行2次更改。show()是问题所在!谢谢你的添加说明,这将帮助我获得更清晰的代码。