QVBoxLayout(topLeftLayout)内容不可见问题求助
解决topLeftLayout内容不显示的问题
问题出在这两点:
- 布局父对象混乱:你创建所有子布局时都把
mainWidget传进去当父对象,这会让每个子布局直接变成mainWidget的顶层布局,根本不会被leftLayout嵌套,层级彻底乱套,topLeftLayout直接被覆盖了。 - 容器未加入窗口显示树:
mainWidget是所有控件的容器,但你从来没把它加到当前的Math窗口里,容器里的控件自然不会显示在窗口上。
怎么改?两种办法任选:
办法1:删掉多余的mainWidget,直接用当前窗口当容器
修改后的代码:
#include "math.h" Math::Math(QWidget* parent) : QWidget(parent) // 保留parent参数符合Qt规范 { // 所有控件的父设为当前窗口(this) titleLabel = new QLabel(this); titleLabel->setText("Math Helper v. 0.0.0"); bottomLabel = new QLabel(this); bottomLabel->setText("Made with C++ and Qt Framework"); aboutQtButton = new QPushButton(this); aboutQtButton->setText("About Qt"); quitButton = new QPushButton(this); quitButton->setText("Quit"); // 创建布局时别传父对象,嵌套布局由父布局管理 topLeftLayout = new QVBoxLayout(); topLeftLayout->addWidget(titleLabel); topLeftLayout->addWidget(bottomLabel); topLeftLayout->addStretch(); bottomLeftLayout = new QHBoxLayout(); bottomLeftLayout->addWidget(aboutQtButton); bottomLeftLayout->addWidget(quitButton); bottomLeftLayout->addStretch(); leftLayout = new QVBoxLayout(); leftLayout->addLayout(topLeftLayout); leftLayout->addLayout(bottomLeftLayout); rightLayout = new QVBoxLayout(); mainLayout = new QHBoxLayout(this); // 顶层布局绑定当前窗口 mainLayout->addLayout(leftLayout); mainLayout->addLayout(rightLayout); setWindowTitle("Math Helper"); setFixedSize(windowWidth, windowHeigth); }
办法2:保留mainWidget,正确设置显示层级
要是你非要留着mainWidget,这么改:
#include "math.h" Math::Math(QWidget* parent) : QWidget(parent) { mainWidget = new QWidget(this); // 给mainWidget指定父为当前窗口,确保它在窗口显示树里 titleLabel = new QLabel(mainWidget); titleLabel->setText("Math Helper v. 0.0.0"); bottomLabel = new QLabel(mainWidget); bottomLabel->setText("Made with C++ and Qt Framework"); aboutQtButton = new QPushButton(mainWidget); aboutQtButton->setText("About Qt"); quitButton = new QPushButton(mainWidget); quitButton->setText("Quit"); // 子布局别传父对象 topLeftLayout = new QVBoxLayout(); topLeftLayout->addWidget(titleLabel); topLeftLayout->addWidget(bottomLabel); topLeftLayout->addStretch(); bottomLeftLayout = new QHBoxLayout(); bottomLeftLayout->addWidget(aboutQtButton); bottomLeftLayout->addWidget(quitButton); bottomLeftLayout->addStretch(); leftLayout = new QVBoxLayout(); leftLayout->addLayout(topLeftLayout); leftLayout->addLayout(bottomLeftLayout); rightLayout = new QVBoxLayout(); mainLayout = new QHBoxLayout(mainWidget); // 把顶层布局绑定给mainWidget mainLayout->addLayout(leftLayout); mainLayout->addLayout(rightLayout); // 给当前窗口加布局,把mainWidget放进去 QVBoxLayout* windowLayout = new QVBoxLayout(this); windowLayout->addWidget(mainWidget); setWindowTitle("Math Helper"); setFixedSize(windowWidth, windowHeigth); }
额外提醒
Qt里嵌套布局不需要指定父对象,父布局会自动管理子布局的显示和生命周期;只有顶层布局需要绑定到widget上,要么创建时传父,要么用setLayout。另外控件的父对象决定了它的显示归属,必须确保容器在窗口的显示树里,不然控件白搭。
内容的提问来源于stack exchange,提问作者Giovanni Scordilli
相关产品推荐
相关产品推荐

