QT开发中文网

QLayout: Attempting to add QLayout "" to MainWindow "MainWindow", which already has a layout QLayout::addChildLayout: layout "verticalLayout" already has a parent QWidget::setLayout: Attempting to set QLayout "" on MainWindow "MainWindow", which a...

这些警告通常是由于重复设置布局或样式表引起的。请确保在添加布局之前,检查是否已经有其他布局被设置。

另外,请注意检查是否有多次设置相同对象的样式表。如果要为 QLabel 设置样式表,只需设置一次即可,不需要重复设置。

以下是一个可能导致上述警告的示例代码:

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    QVBoxLayout* layout = new QVBoxLayout(this);  // 创建一个垂直布局
    QLabel* label = new QLabel("Hello World", this);
    
    // 错误:尝试将 QLayout 添加到已经具有布局的 MainWindow 上
    setLayout(layout);
    
    // 错误:多次设置相同对象的样式表
    label->setStyleSheet("color: red;");
    label->setStyleSheet("font-size: 14px;");

    layout->addWidget(label);  // 向布局中添加标签
}

为了解决这些问题,请确保只在必要时设置布局,并避免重复设置对象的样式表。以下是修正后的代码片段:

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    QVBoxLayout* layout = new QVBoxLayout();
    
    QLabel* label = new QLabel("Hello World");
    
   // 将标签放入一个容器 widget 中
   QWidget* containerWidget = new QWidget();
   containerWidget->setLayout(layout);
    
   setCentralWidget(containerWidget);  // 设置容器 widget 作为中心窗口
    
   label->setStyleSheet("color: red; font-size: 14px;");
    
   layout->addWidget(label);
}

通过创建一个容器 widget,并将布局设置给它,然后将该容器 widget 设置为中心窗口,可以解决布局相关的问题。并且确保只设置一次对象的样式表即可避免样式表相关的警告。


内容由零声教学AI助手提供,问题来源于学员提问

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://qt.0voice.com/?id=11846

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?