tetra
tetra

Reputation: 197

Error handling and showing QMessageBox in the Main.cpp

Can I show a kind of "instant" message box in the main.cpp before showing the MainWindow.cpp?

In the below code, I'm opening a serial port and there are two connect statements and then it shows the main window. Now, I need to alert the user with a QMessagebox if someting goes wrong with opening serial port (and then terminate the program).

How can I do that in the main.cpp?

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    api.openSerialPort();

    QObject::connect(api.serial, SIGNAL(readyRead()), &api, SLOT(readData()));
    QObject::connect(api.serial, SIGNAL(error(QSerialPort::SerialPortError)),&api, SLOT(ErrorHandler(QSerialPort::SerialPortError))); // error handling

    StageOneMain w(nullptr);
    w.show();
    return a.exec();
}

Upvotes: 0

Views: 627

Answers (1)

Minh
Minh

Reputation: 1725

The function QSerialPort::open() returns a boolean value to indicate if successful.

#include "mainwindow.h"

#include <QApplication>
#include <QMessageBox>
#include <QSerialPort>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;
    QSerialPort serial_port;
    // connecting stuffs
    if (serial_port.open(QIODevice::ReadWrite))
        w.show();
    else
        QMessageBox::warning(nullptr, QObject::tr("Open serial port error"), serial_port.errorString());
    return a.exec();
}

Upvotes: 1

Related Questions