Search code examples
c++qtstaticqt4shared-libraries

QMessageBox in a shared library throwing error


I created a shared library in QT to create a user defined static message box with following modules selected (class code given below). QtCore, QtGui, QtWidgets. But it is throwing error.

Below is the library class that is throwing error.
//Header File

class Q_DECL_EXPORT cMessageBox
    {
      private:
           static QMessageBox msgbox;
      public:
           cMessageBox();
           ~cMessageBox();
           static void CustomMessageBox(QString strTitle,QString strMessage);
    };

//CPP file

QMessageBox cMessageBox::msgbox;

cMessageBox::cMessageBox(){}

cMessageBox::~cMessageBox(){}

void cMessageBox::CustomMessageBox(QString strTitle, QString strMessage){
     msgbox.setWindowTitle(strTitle);
     msgbox.setText(strMessage);
     msgbox.exec();
}

//Used as

cMessageBox::CustomMessageBox("Title","Message");

Error is

[
QWidget: Must construct a QApplication before a QWidget
Invalid parameter passed to C runtime function.
Invalid parameter passed to C runtime function.
exited with code 3
]

If i remove the static for both the QMessageBox and the CustomMessageBox method, then it is working fine (library used code given below). What error i did, when using static keyword.

cMessageBox msg;
msg.CustomMessageBox("Title","Message");

Solution

  • The reason is, static objects are initialized before the main method runs. Hence, QApplication is never initialized before you make QMessagebox object. Hence, we usually don't create static QWidgets. (I don't know a remedy to that) This may not solve your problem. But at least we know what is wrong.

    See this for more info.

    Must construct a QApplication before a QWidget