打开窗口qt时应用程序崩溃

Application crashes when opening a window qt

本文关键字:应用程序 崩溃 qt 开窗口      更新时间:2023-10-16

我想创建一个程序,向用户显示一个带有一些答案的问题。我的应用程序使用了3种形式:主菜单、登录菜单和游戏表单,它们都继承了一个名为Form的抽象类;我这样做是因为它允许使用工厂方法,当实际形式发出信号GoFw时,它会创建一个新窗口。

显示窗口的"循环"如下:MainMenu->LoginMenu->GameForm->MainMenu。。。问题是当游戏结束时(例如,剩余问题的计数为零),GameForm会发出信号GoFw,但在show()方法之后应用程序崩溃(在崩溃之前,我可以看到一个没有按钮的白色窗口)。调试器显示一个包含以下错误的消息框:

The inferior stopped because it triggered an exception.
Stopped in thread 0 by: Exception at 0x723f7b93, code: 0xc0000005: read access
violation at: 0x0, flags=0x0 (first chance).

QtCreator打开一个名为:Disassembler(QHash::findNode)的文件

这是工厂的代码方法:

void FormFactory::Init(int formType)
{
    ///if formType == 1 MainMenu is showed
    if(formType == MAIN_MENU_TYPE)
    {
        //inizializza il puntatore
        actualForm = new MainMenu();
    }
    ///else if is == 2 show ProfileMenu
    else if(formType == PROFILE_MENU_TYPE)
    {
        actualForm = new LoginMenu();
    }
    ///else if == 3 show GameForm
    else if(formType == GAME_FORM_TYPE)
    {
        actualForm = new GameForm();
    }
    ///else if there is no match launch an exception
    else
        throw UnexpectedIdEx();
    connect(actualForm, SIGNAL(GoFw(int)), this, SLOT(DisplayForm(int)));
}
void FormFactory::DisplayForm(int i)
{
    Reset();
    Init(i);
    ///show the form pointed by actualform
    actualForm->show();
}
void FormFactory::Reset()
{
    disconnect(actualForm, SIGNAL(GoFw(int)), this, SLOT(DisplayForm(int)));
    ///if actualform is actually pointing to a form, delete it and set actualForm to zero
    if(actualForm!=0)
        delete actualForm;
    actualForm = 0;
}

MainMenu.cpp的代码是

MainMenu::MainMenu()
{
    setUpGui();
}
void MainMenu::setUpGui()
{
    playButton = new QPushButton(tr("Play"));
    infoButton = new QPushButton(tr("Info"));
    quitButton = new QPushButton(tr("Exit"));
    ///connect the clicked signal to the related slot
    connect(infoButton, SIGNAL(clicked()), this, SLOT(info()));
    connect(quitButton, SIGNAL(clicked()), this, SLOT(quit()));
    connect(playButton, SIGNAL(clicked()), this, SLOT(emitSig()));
    ///create the vertical layout
    QVBoxLayout *layout = new QVBoxLayout;
    layout->addWidget(playButton);
    layout->addWidget(infoButton);
    layout->addWidget(quitButton);
    setLayout(layout);
    setWindowTitle(tr("Menu Principale"));
}
void MainMenu::emitSig()
{
    emit GoFw(2);
}

谢谢大家的帮助,Luca

我建议重新思考您的解决方案,因为您似乎将其与工厂方法过于复杂。只需对表单使用3个变量,对每个变量执行一次"new"操作,并根据信号使用show()/hide()方法。

为了解决崩溃问题,我看到的一个原因是你在插槽中进行了"删除"。来自Qt文档:

警告:在等待传递挂起事件时删除QObject可能会导致崩溃。如果QObject存在于与当前执行的线程不同的线程中,则不能直接删除它。改为使用deleteLater(),这将导致事件循环在所有挂起的事件都传递到对象后删除该对象。