Qt:不使用Qt Designer在main.cpp中显示MainWindow的问题
解决方案
你的问题出在mainwindow.cpp里创建了一个局部的QMainWindow对象,这个对象在构造函数执行完毕后会被销毁,所以界面无法持续显示。正确的做法是让你的MainWindow类直接继承QMainWindow,并在构造函数中直接操作当前实例(this),而不是新建一个独立的QMainWindow对象。
步骤1:修正mainwindow.h
确保MainWindow类继承自QMainWindow,头文件示例如下:
#ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> class MainWindow : public QMainWindow { Q_OBJECT public: MainWindow(QWidget *parent = nullptr); }; #endif // MAINWINDOW_H
步骤2:修正mainwindow.cpp
在构造函数中直接使用this作为主窗口实例,设置中央部件和布局,示例代码:
#include "mainwindow.h" #include <QWidget> #include <QVBoxLayout> MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) { // 创建中央部件,作为主窗口的核心容器 QWidget *centralWidget = new QWidget(this); setCentralWidget(centralWidget); // 给中央部件设置布局 QVBoxLayout *layout = new QVBoxLayout(centralWidget); // 这里可以继续添加你的其他控件,比如按钮、标签等 // 示例:QPushButton *btn = new QPushButton("测试按钮", centralWidget); // layout->addWidget(btn); // 设置主窗口初始大小 resize(600, 400); }
步骤3:main.cpp保持不变
你的原main.cpp代码无需修改,调用w.show()即可正常显示界面:
#include "mainwindow.h" #include <QApplication> int main(int argc, char *argv[]) { QApplication a(argc, argv); MainWindow w; w.show(); return a.exec(); }
这样修改后,GUI代码完全封装在MainWindow类中,实现了代码分离,同时能正常显示界面。
内容的提问来源于stack exchange,提问作者Lebo
相关产品推荐
相关产品推荐

