递归构造函数致程序崩溃?Qt代码模仿问题求助
Why Your Qt App Crashes When Creating MainWindow via the ui Pointer
Hey there! You’re totally right to suspect infinite recursion—that’s exactly the culprit behind your crashing app when trying to create a new MainWindow instance using the ui pointer. Let’s break this down step by step:
What’s Going Wrong Here?
First, let’s clear up what the ui pointer is actually for:
- The
uipointer is auto-generated by Qt Designer, and it points to the UI elements of your currentMainWindowinstance (think buttons, labels, layouts, etc.). Its sole purpose is to let you access and manipulate the interface of the window it belongs to—not to create new window objects.
If you’re writing code like this (likely inside your MainWindow constructor or a method that runs during initialization):
// Wrong approach! // Example of the problematic pattern (even if syntax varies slightly) ui->someFunctionThatCreatesMainWindow(); // Or directly trying to instantiate via ui (invalid, but similar logic causes issues)
You’re triggering an infinite loop of creation:
- The first
MainWindowis created, and its constructor runs. - Inside that constructor, you attempt to make another
MainWindow(via a misuseduipointer or code triggered by it). - This new
MainWindowruns its own constructor, which again tries to create anotherMainWindow... - This repeats until your program runs out of stack memory, leading to a crash.
The Correct Way to Create a New MainWindow
To safely open a new MainWindow instance, do it directly (not via the ui pointer) in a proper context—like a button click slot function. Here’s a concrete example:
// Inside your MainWindow.cpp #include "MainWindow.h" #include "ui_MainWindow.h" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) , ui(new Ui::MainWindow) { ui->setupUi(this); // Connect a button to trigger opening a new window connect(ui->openNewWindowBtn, &QPushButton::clicked, this, &MainWindow::openNewWindow); } MainWindow::~MainWindow() { delete ui; } void MainWindow::openNewWindow() { // Create a new MainWindow instance MainWindow *newWindow = new MainWindow(this); // Setting a parent helps with memory management newWindow->show(); // Optional: If you don't set a parent, use deleteLater() to avoid memory leaks // connect(newWindow, &QMainWindow::destroyed, newWindow, &QObject::deleteLater); }
Key Takeaways
- Don’t use the
uipointer to create new windows: It’s only meant for accessing the current window’s UI elements. - Avoid creating
MainWindowinstances inside its own constructor: This is a guaranteed path to infinite recursion. - Manage memory wisely: Use parent-child relationships or
deleteLater()to ensure your windows don’t leave memory leaks.
内容的提问来源于stack exchange,提问作者strikeforcefan2013
相关产品推荐
相关产品推荐

