Qt:更改 centralWidget 时崩溃

Qt: crash when changing centralWidget

本文关键字:崩溃 centralWidget 更改 Qt      更新时间:2023-10-16

我创建了自己的类,这里是ewindow.h

#ifndef EWINDOW_H
#define EWINDOW_H
#include <QWidget>
#include <QString>
#include <mainwindow.h>
class MainWindow;
class EWindow
{
    public:
        EWindow(void (*callback)(EWindow*, MainWindow*), MainWindow *window, QString name, QString title);
        QWidget *widget;
        void resize(int width, int height);
        void move(int x, int y);
        void move();
        void apply();
        void append(QWidget *newWidget);
        int* getSize();
        ~EWindow();
    private:
        int width, height, x, y;
        QString name, title;
        MainWindow *window;
};
#endif // EWINDOW_H

构造 函数:

EWindow::EWindow(void (*callback)(EWindow*, MainWindow*), MainWindow *window, QString name, QString title) {
    this->width = 0;
    this->height = 0;
    this->x = -1;
    this->y = -1;
    this->name = name;
    this->title = title;
    this->window = window;
    this->widget = new QWidget();
    (*callback)(this, window);
}

在回调中,我创建了一些小部件,例如QLabelQLineEdit。这是我的apply函数:

void EWindow::apply() {
    window->setCentralWidget(this->widget);
    window->setWindowTitle(this->title);
    window->setFixedWidth(this->width);
    window->setFixedHeight(this->height);
    if (this->x == -1 || this->y == -1) this->move();
    window->move(this->x, this->y);
}

但!当我尝试为不同的 EWindows 调用应用函数 2 次时,我的程序崩溃而没有任何错误。我认为这一行有错误:window->setCentralWidget(this->widget);.请帮忙,谢谢。

没有问题了。我忘记了Qt在应用new时会删除以前的QWidget。我是这样做的:

回调不会在构造函数中调用,只会在函数apply()中调用,在创建QWidget的新实例后。现在它工作得很好。谢谢,drescherjm