c++ - 如何在 Main() 之外创建和显示 MainWindow?

标签 c++ qt qt-creator

我在网上做了很长时间的研究,但找不到任何明确的信息。 我认为答案很明显,但我是 Qt 的初学者。 为什么这段代码不起作用?我的窗口弹出速度非常快。

main.cpp

#include <QApplication>
#include "test.h"

int main(int argc, char *argv[])
{
QApplication a(argc, argv);
Test test;

return a.exec();
}

测试.cpp

#include "test.h"

Test::Test()
{
 MainWindow w;
 w.show();
}   

这一项有效(窗口保持打开状态):

#include "mainwindow.h"
#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;
    w.show();
    return a.exec();
}

谢谢!

最佳答案

窗口关闭,因为它是 Test 构造函数的局部变量,当构造函数退出时,将调用其析构函数,从而将其关闭。你需要让window对象成为Test类的成员变量。

关于c++ - 如何在 Main() 之外创建和显示 MainWindow?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41600681/

相关文章:

c++ - 如果类型不是指针,如何限制调用模板函数?

C++智能指针

c++ - 我可以从 STA dll 运行 QT 或 wxWidgets GUI 吗?

c++ - 错误 : C2664: 'QXmlStreamWriter::writeAttributes' : cannot convert parameter 1 from 'QVector<T>' to 'const QXmlStreamAttributes &'

profiling - gperftools - 配置文件未转储

.net - 在 C++ 中重载运算符,然后在 VB.NET 中导出和导入

android - 了解 Android Native 代码崩溃报告

linux - 在 Windows 中字体显示为斜体,但在 Linux 中它始终显示为粗体

qt - 如何在 qt creator 中指定不同的工作目录?

c++ - 在 Qt Creator 中创建新的 Symbian 应用程序时, "Target UID3"是什么意思?