qt切换中心小部件时出现分段错误而导致程序崩溃

问题描述 投票:0回答:1

我可能尝试了所有方法,但在此代码中看不到任何错误。我制作了两个从QMainWindow继承的窗口:一个带有qt设计器,另一个带有构造器。我试图根据您按下的按钮在MainWindow类中切换这些窗口。

  1. LoginWindow.cpp
LoginWindow::LoginWindow(QWidget *parent): QMainWindow(parent), ui(new Ui::LoginWindow) {
    ui->setupUi(this);
}

LoginWindow::~LoginWindow() {
    delete ui;
}


void LoginWindow::on_confirmButton_clicked() {
    emit confirmButton_clicked();
}

  1. RegistrationWindow.hpp
RegistrationWindow::RegistrationWindow(QWidget* parent): QMainWindow(parent) {

    label = new QLabel("Fast Typing"); //variable in .hpp
    label->setAlignment(Qt::AlignCenter);
    label->setFont(QFont("Lucida Console", 12, 2));
    QVBoxLayout * l = new QVBoxLayout();
    l->addWidget(label);
    l->addWidget(new QLabel("Login", this));
    l->addWidget(new QLineEdit(this));
    l->addWidget(new QLabel("Password", this));
    l->addWidget(new QLineEdit(this));
    p = new QPushButton("Confirm", this); //variable in .hpp
    l->addWidget(p);
    w = new QWidget(); //variable in .hpp
    w->setLayout(l);
    setCentralWidget(w);

    connect(p, &QPushButton::clicked, this, &RegistrationWindow::on_confirmButton_clicked);
}

void RegistrationWindow::on_confirmButton_clicked() {
    emit confirmButton_clicked();
}

RegistrationWindow::~RegistrationWindow() { }
  1. MainWindow.cpp
MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) {
    //variables in .hpp
    logWindow = new LoginWindow();
    regWindow = new RegistrationWindow();
    goToReg();

    connect(logWindow, SIGNAL(confirmButton_clicked()), this, SLOT(goToReg()));
    connect(regWindow, SIGNAL(confirmButton_clicked()), this, SLOT(goToLog()));
}

void MainWindow::goToReg() {
    qDebug() << "goToReg";
    resize(regWindow->size());
    qDebug() << "goToReg";
    setCentralWidget(regWindow);
    setWindowTitle("Registration");
    qDebug() << "registration: " << regWindow;
    qDebug() << "login: " << logWindow;
}

void MainWindow::goToLog() {
    qDebug() << "goToLog";
    resize(logWindow->size());
    qDebug() << "goToLog";
    setCentralWidget(logWindow);
    setWindowTitle("Login");
    qDebug() << "registration: " << regWindow;
    qDebug() << "login: " << logWindow;
}

[我只能说,无论我做哪个起始窗口,它都会切换窗口,第二次它会在插槽中的setCentralWidget()崩溃,并出现SEGV运行时错误。

c++ qt qmainwindow
1个回答
0
投票

来自the documentationQMainWindow::setCentralWidget

注意:QMainWindow拥有窗口小部件指针的所有权,并在适当的时间将其删除。

logWindowregWindow指向开始生活的小部件不存在。然后,您调用goToReg(),后者又调用了setCentralWidget(regWindow)-现在主窗口拥有*regWindow。然后,您调用goToLog(),这又调用了setCentralWidget(logWindow)-现在主窗口拥有*logWindowdestroys *regWindow的所有权,因此regWindow变成了悬空指针。下次尝试使用它时,该程序表现出未定义的行为。

© www.soinside.com 2019 - 2024. All rights reserved.