質問

I'm trying to connect a signal from one class to a slot in another class but when I do, my application crashes on startup. I read some other posts on here and the Qt forums that eluded to connecting custom signals as such but I think I'm connecting them wrong. Any help is greatly appreciated.

AdministrativeWindow.h

class AdministrativeWindow : public QMainWindow
{
    Q_OBJECT

    public:
        explicit AdministrativeWindow(QWidget *parent = 0);
        ~AdministrativeWindow();

    private slots:
        void on_actionExit_Administrative_Window_triggered();

    private:
        Ui::AdministrativeWindow *ui;

    signals:
        void windowClose();
};

AdministrativeWindow.cpp

void AdministrativeWindow::on_actionExit_Administrative_Window_triggered()
{
    emit windowClose();
    close();
}

MainWindow.cpp

connect(adminWindow, SIGNAL(windowClose()), this, SLOT(adminWindowClose()));

void MainWindow::on_ConfigureUsersBtn_clicked()
{
    if(adminWindow == NULL)
    {
        adminWindow = new AdministrativeWindow();
        adminWindow->show();
    }
    else if(adminWindow->isVisible())
    {
        adminWindow->activateWindow();
        adminWindow->showNormal();
    }
    else
    {
        adminWindow->show();
    }
}

void MainWindow::on_adminWindowClose()
{
    delete adminWindow;
    adminWindow = NULL;
}
役に立ちましたか?

解決

You need to ensure that you're using valid adminWindow pointer on connect:

void MainWindow::on_ConfigureUsersBtn_clicked()
{
    if(adminWindow == NULL)
    {
        adminWindow = new AdministrativeWindow();
        connect(adminWindow, SIGNAL(windowClose()), this, SLOT(adminWindowClose()));
        adminWindow->show();
    }

他のヒント

be sure to do a connect after pointer has been initialized

connect(adminWindow, SIGNAL(windowClose()), this, SLOT(adminWindowClose()));
           ^
        valid ptr

also private slots are private if called as regular member functions but always public for connection. I think this is cleaner design to define slots as public since their purpose is communication and use private functions as usual when they are needed unless you really need such mixed concept as private slot (it might exist however and one can imagine some special circumstances in which this might have sense, I assume this is not the case here)

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top