Qt error: “Must construct a QApplication before a QWidget”



  • Hi.
    I have a big project (with a lot of page widget that I cant copy all of them here).
    yesterday all of them work good. Today I change several pages that they do not have any errors. but when I run project write successful build, **but show me this error :

    Starting /home/hgh1/prj/TimeAssistant/1395-02/VS200/VS200/build-VS200-Desktop4_6-Debug/VS200...
    QWidget: Must construct a QApplication before a QPaintDevice
    The program has unexpectedly finished.
    /home/hgh1/prj/TimeAssistant/1395-02/VS200/VS200/build-VS200-Desktop4_6-Debug/VS200 crashed
    

    I changed all the code that I changed them today. but again show me this error.
    When I put break point in main.cpp in first line : Application a(argc,argv); this is not work and again show this error.(on Ubuntu Linux OS).

    I decide to copy step by step the classes and main.cpp and mainwindow.h .cpp .ui.
    but when I run project show me another strange error :

    /opt/DesktopQt4.8.6/include/QtGui/qtextformat.h:699: error: macro "border" requires 8 arguments, but only 1 given
         inline qreal border() const
    

    this line error is in qtextformat.h .
    or this error :

    /opt/DesktopQt4.8.6/include/QtGui/qgraphicsitem.h:347: error: variable or field 'scroll' declared void
         void scroll(qreal dx, qreal dy, const QRectF &rect = QRectF());
              ^
    /opt/DesktopQt4.8.6/include/QtGui/qtextformat.h:700: error: expected unqualified-id before '{' token
         { return doubleProperty(FrameBorder); }
         ^
    


  • In technical terms: your code has a bug.

    You really should bring your source code exactly back to what it was when your app last worked.

    Try to be exact with your information and try to find the first point in the workflow when something fails. For example, problems in header files are raised during compiling, not when you run your app.

    And since the last ones are compiler errors, they could be anywhere in your application, but since your app actually executed before the last edits, and where you did the editing, you have or had a problem in the code that constructs you QApplication derived object or refers to it. Anyway, the problems should be in your .cpp files and nobody can know where, unless you show them.

    Note that if you only look at the Issues pane, you could find more information in the Compile Output pane.


  • Moderators

    The first error is common when you create a global static instance of a QObject derived class. It doesn't have to be static itself, just for example part of another static struct/class.
    The other errors look like either missing includes or include pollution i.e. something included before Qt defines some names that Qt uses.
    Beyond that - basically what @mvuori said - roll back to last working state (hopefully you used some version control system) and compare differences.



  • @mvuori : thanks for reply.
    @chris thanks. I dont have any global static variables. and also thanks for your advice to use version control. I should use it when my program run successfully.
    I can not bring back because I forget . :(
    there is nothing on Issues pane when build successfully.
    this is my project :
    DB --->class for database
    PortSerial----->config serial port
    inputpanel and inputpanelcontext ---> copy this project from this link
    those are my main class that they do not have any error.
    this is main.cpp:

    #include "mainwindow.h"
    #include <QApplication>
    #include "myinputpanelcontext.h"
    
    
    int main(int argc, char *argv[])
    {
        QApplication a(argc, argv);
        MyInputPanelContext *ic= new MyInputPanelContext; ;
        a.setInputContext(ic);
        MainWindow w;
        w.show();
        //w.showFullScreen();
    
        return a.exec();
    }
    

    mainwindow.h

    #ifndef MAINWINDOW_H
    #define MAINWINDOW_H
    
    #include <QMainWindow>
    #include <QTimer>
    #include <QDate>
    #include <QTime>
    #include "menu.h"
    #include <QMessageBox>
    #include <QSocketNotifier>
    #include "db.h"
    #include "portserial.h"
    #include "usermng.h"
    #include <QPaintDevice>
    #include <QPushButton>
    
    namespace Ui {
    class MainWindow;
    }
    
    class MainWindow : public QMainWindow
    {
        Q_OBJECT
    
    public:
        QTimer *timer ;
        DB *database;
        PortSerial *serialport;
        QSocketNotifier *notifier ;
        explicit MainWindow(QWidget *parent = 0);
        ~MainWindow();
    
    private slots:
         void ReadAndProcessData();
        void SetupUI();
        void SetButtonImage(QPushButton *btn,QString Path);
        void ShowTime();
        void on_btnMenu_clicked();
        void on_btnEnter_clicked();
        void on_btnShowFunctions_clicked();
    
    private:
        Ui::MainWindow *ui;
    };
    
    #endif // MAINWINDOW_H
    
    

    mainwindow.cpp

    
    #include "mainwindow.h"
    #include "ui_mainwindow.h"
    #include <QSound>
    #include <Qt/QtMultimedia>
    
    bool typing;
    bool showmenu;
    UserMng *mf;
    QMessageBox msg;
    QString msgerr;
    
    MainWindow::MainWindow(QWidget *parent) :
        QMainWindow(parent),
        ui(new Ui::MainWindow)
    {
        ui->setupUi(this);
        serialport=new PortSerial();
        database=new DB();
        serialport->openport();
        mf=NULL;
        /*set the timer*/
        timer=new QTimer(this);
        connect(timer, SIGNAL(timeout()), this, SLOT(ShowTime()));
        timer->start(1000);
        SetupUI();
        ui->lblDate->setText(QDate::currentDate().toString("yy/MM/dd"));
        typing=false;
        showmenu=false;
        ui->statusBar->addWidget(ui->lbl_text,0);
        ui->lbl_text->setText("the status of device");
        if(database->openConnection())
        {
            notifier=new QSocketNotifier(serialport->fd, QSocketNotifier::Read,this);
            notifier->setEnabled(true);
            connect(this->notifier,SIGNAL(activated(int)),this,SLOT(ReadAndProcessData()));
        }
        else
            ui->lbl_text->setText("the database can not open.");
    }
    
    MainWindow::~MainWindow()
    {
        delete ui;
    }
    //======================================
    //           Setup UI
    //======================================
    ///
    /// \brief MainWindow::SetupUI
    ///
    void MainWindow::SetupUI()
    {
        /*set transparent farem*/
          this->setStyleSheet("QMainWindow {background-image: url(1.jpg);background-repeat:no-repeat;background-position:center;}");
        //==============================================
        /*menu frame enter password*/
        ui->gbPassWord->setVisible(false);
        //ui->txtPassword->setEchoMode(QLineEdit::Password);
        //==============================================
        /*Set the image icon*/
         SetButtonImage(ui->btnMenu,"/pic/menu.png");
        //=============================================
        /*Set the menubar tool bar*/
        ui->mainToolBar->setVisible(false);
        ui->menuBar->setVisible(false);
        //=============================================
        ui->gbFunction->setGeometry(140,-150,431,201);
    }
    
    void MainWindow::SetButtonImage(QPushButton *btn,QString Path)
    {
        QString str=(qApp->applicationDirPath());
        str.append(Path);
        QPixmap pixmap(str);
        QIcon ButtonIcon(pixmap);
        btn->setIcon(ButtonIcon);
        btn->setIconSize(pixmap.rect().size());
    }
    
    
    
    void MainWindow::ShowTime()
    {
        QTime time = QTime::currentTime();
        QString text = time.toString("hh:mm");
        ui->lblTime->setText(text);;
    }
     /*Menu frame*/
    //============================================
    void MainWindow::on_btnMenu_clicked()
    {
        if(showmenu)
        {
            showmenu=false;
            ui->gbPassWord->setVisible(true);;
        }
        else
        {
            showmenu=true;
            ui->gbPassWord->setVisible(false);;
        }
    }
    //============================================
    void MainWindow::on_btnEnter_clicked()
    {
        if(ui->btnEnter->text()=="Enter password")
        {
            if (ui->txtPassword->text()==database->CheckAttendant(ui->lbl_text->text()))
            {
    //            database->InsertAttendant(ui->lbl_text->text());
    //              QSound::play("welcome.wav");//qApp->applicationDirPath() +
    //              ui->btnEnter->setText("Enter");
    //              ui->gbPassWord->hide();
            }
            else
            {
                msgerr="PASSWORD NOT ACCEPT!!!!!!.";
                msg.setIcon(QMessageBox::Warning);
                msg.setStandardButtons(QMessageBox::Ok);
                msg.setText(msgerr);
                msg.exec();
                ui->btnEnter->setText("Enter");
                ui->gbPassWord->hide();
            }
        }
        else
        {
            if(ui->txtPassword->text()=="1234")
            {
                ui->txtPassword->setText("");
                menu *m=new menu;
                m->showFullScreen();
                //m->show();
                //this->hide();
            }
        }
    
    }
    //============================================
    void MainWindow::on_btnShowFunctions_clicked()
    {
        ui->gbFunction->setGeometry(140,210,431,201);
    }
    //============================================
    //                                      READ FROM CARD
    //============================================
    
    void MainWindow::ReadAndProcessData()
    {
        QString output;
        serialport->readcard(output);
    
        //menu* m;
        if(mf!=NULL)
        {
            mf->processData(output);
        }
        else
        {
    
            msgerr=database->CheckAttendant(output);
            if (msgerr=="Error1")
            {
                msgerr="DataBase error occured.";
                msg.setIcon(QMessageBox::Warning);
                msg.setStandardButtons(QMessageBox::Ok);
                msg.setText(msgerr);
                msg.exec();
            }
            if (msgerr.length()==0)
            {
                //play sound this user have nou password
                QSound::play("welcome.wav");//qApp->applicationDirPath() +
                database->InsertAttendant(output);
            }
           if (msgerr.length()>0)
            {
                ui->gbPassWord->show();
                ui->btnEnter->setText("Enter password");
                ui->lbl_text->setText(output);
            }
    
    
        }
    
        notifier->setEnabled(true);
    
    }
    
    
    

    mainwindow.ui

    <?xml version="1.0" encoding="UTF-8"?>
    <ui version="4.0">
     <class>MainWindow</class>
     <widget class="QMainWindow" name="MainWindow">
      <property name="geometry">
       <rect>
        <x>0</x>
        <y>0</y>
        <width>726</width>
        <height>469</height>
       </rect>
      </property>
      <property name="windowTitle">
       <string>MainWindow</string>
      </property>
      <property name="styleSheet">
       <string notr="true">color:white;font-size:12px;background-color:rgba(255,255,255,10);</string>
      </property>
      <widget class="QWidget" name="centralWidget">
       <widget class="QLabel" name="lblTime">
        <property name="geometry">
         <rect>
          <x>10</x>
          <y>110</y>
          <width>151</width>
          <height>17</height>
         </rect>
        </property>
        <property name="font">
         <font>
          <pointsize>-1</pointsize>
         </font>
        </property>
        <property name="styleSheet">
         <string notr="true">color:white;
    font-size:12px;</string>
        </property>
        <property name="text">
         <string>Time</string>
        </property>
       </widget>
       <widget class="QLabel" name="lblDate">
        <property name="geometry">
         <rect>
          <x>10</x>
          <y>140</y>
          <width>151</width>
          <height>17</height>
         </rect>
        </property>
        <property name="font">
         <font>
          <pointsize>-1</pointsize>
         </font>
        </property>
        <property name="styleSheet">
         <string notr="true">color:white;
    font-size:12px;</string>
        </property>
        <property name="text">
         <string>Date </string>
        </property>
       </widget>
       <widget class="QGroupBox" name="gbFunction">
        <property name="geometry">
         <rect>
          <x>140</x>
          <y>-150</y>
          <width>431</width>
          <height>201</height>
         </rect>
        </property>
        <property name="styleSheet">
         <string notr="true">QGroupBox{background-color:rgba(255,255,255,0.5);border-style:none;}
    QPushButton
    {
    background-color: #4CAF50; /* Green */
        border: none;
        color: white;
        padding: 5px 10px;
        text-align: center;
        text-decoration: none;
        font-size: 12px;
    }</string>
        </property>
        <property name="title">
         <string/>
        </property>
        <widget class="QPushButton" name="btnShowFunctions">
         <property name="geometry">
          <rect>
           <x>0</x>
           <y>160</y>
           <width>431</width>
           <height>41</height>
          </rect>
         </property>
         <property name="text">
          <string> Functions</string>
         </property>
        </widget>
        <widget class="QWidget" name="layoutWidget">
         <property name="geometry">
          <rect>
           <x>30</x>
           <y>10</y>
           <width>371</width>
           <height>131</height>
          </rect>
         </property>
         <layout class="QGridLayout" name="gridLayout_2">
          <item row="0" column="0">
           <widget class="QPushButton" name="pushButton">
            <property name="text">
             <string>PushButton</string>
            </property>
           </widget>
          </item>
          <item row="0" column="1">
           <widget class="QPushButton" name="pushButton_2">
            <property name="text">
             <string>PushButton</string>
            </property>
           </widget>
          </item>
          <item row="0" column="2">
           <widget class="QPushButton" name="pushButton_3">
            <property name="text">
             <string>PushButton</string>
            </property>
           </widget>
          </item>
          <item row="0" column="3">
           <widget class="QPushButton" name="pushButton_4">
            <property name="text">
             <string>PushButton</string>
            </property>
           </widget>
          </item>
          <item row="1" column="0">
           <widget class="QPushButton" name="pushButton_5">
            <property name="text">
             <string>PushButton</string>
            </property>
           </widget>
          </item>
          <item row="1" column="1">
           <widget class="QPushButton" name="pushButton_7">
            <property name="text">
             <string>PushButton</string>
            </property>
           </widget>
          </item>
          <item row="1" column="2">
           <widget class="QPushButton" name="pushButton_8">
            <property name="text">
             <string>PushButton</string>
            </property>
           </widget>
          </item>
          <item row="1" column="3">
           <widget class="QPushButton" name="pushButton_6">
            <property name="text">
             <string>PushButton</string>
            </property>
           </widget>
          </item>
         </layout>
        </widget>
       </widget>
       <widget class="QGroupBox" name="gbPassWord">
        <property name="geometry">
         <rect>
          <x>140</x>
          <y>210</y>
          <width>431</width>
          <height>81</height>
         </rect>
        </property>
        <property name="styleSheet">
         <string notr="true">*{color:white;font-size:14px;}
    QLineEdit{
    background-color: #fff;
        border: 1px solid #ddd;
    	font-size:14px;
        color: #32373c;
    }
    QLineEdit:hover{
    border-color: #D2691E;
    border-radius:5px;
       
    }
    QGroupBox{background-color:rgba(255,255,255,0.5);border-style:none;}
    QPushButton
    {
    background-color: #4CAF50; /* Green */
        border: none;
        color: white;
        padding: 5px 10px;
        text-align: center;
        text-decoration: none;
        font-size: 12px;
    }</string>
        </property>
        <property name="title">
         <string/>
        </property>
        <widget class="QWidget" name="layoutWidget">
         <property name="geometry">
          <rect>
           <x>10</x>
           <y>20</y>
           <width>411</width>
           <height>51</height>
          </rect>
         </property>
         <layout class="QHBoxLayout" name="horizontalLayout">
          <item>
           <widget class="QLabel" name="label">
            <property name="text">
             <string>Enter your password please:</string>
            </property>
           </widget>
          </item>
          <item>
           <widget class="QLineEdit" name="txtPassword"/>
          </item>
          <item>
           <widget class="QPushButton" name="btnEnter">
            <property name="text">
             <string>Enter</string>
            </property>
           </widget>
          </item>
         </layout>
        </widget>
       </widget>
       <widget class="QPushButton" name="btnMenu">
        <property name="geometry">
         <rect>
          <x>270</x>
          <y>350</y>
          <width>146</width>
          <height>45</height>
         </rect>
        </property>
        <property name="text">
         <string/>
        </property>
       </widget>
       <widget class="QLabel" name="lbl_text">
        <property name="geometry">
         <rect>
          <x>30</x>
          <y>340</y>
          <width>151</width>
          <height>17</height>
         </rect>
        </property>
        <property name="font">
         <font>
          <pointsize>-1</pointsize>
         </font>
        </property>
        <property name="styleSheet">
         <string notr="true">color:white;
    font-size:12px;</string>
        </property>
        <property name="text">
         <string>--------------------------</string>
        </property>
       </widget>
      </widget>
      <widget class="QMenuBar" name="menuBar">
       <property name="geometry">
        <rect>
         <x>0</x>
         <y>0</y>
         <width>726</width>
         <height>20</height>
        </rect>
       </property>
      </widget>
      <widget class="QToolBar" name="mainToolBar">
       <property name="styleSheet">
        <string notr="true">QLabel{color:white;font-size:12px;}</string>
       </property>
       <attribute name="toolBarArea">
        <enum>TopToolBarArea</enum>
       </attribute>
       <attribute name="toolBarBreak">
        <bool>false</bool>
       </attribute>
      </widget>
      <widget class="QStatusBar" name="statusBar"/>
     </widget>
     <layoutdefault spacing="6" margin="11"/>
     <resources/>
     <connections/>
    </ui>
    

    when I put breakpoints in main.cpp for '{' it shows me SIGABRT error.the line number3 show error. in qglobal.cpp

    0	__kernel_vsyscall			0xb7fdd424	
    1	__GI_raise		56	0xb6fd5827	
    2	__GI_abort		89	0xb6fd8c53	
    3	qt_message_output	qglobal.cpp	2266	0xb72e889d	
    4	qt_message	qglobal.cpp	2312	0xb72e8a47	
    5	qFatal	qglobal.cpp	2495	0xb72e8fb8	
    6	QWidgetPrivate::QWidgetPrivate	qwidget.cpp	213	0xb7693286	
    7	QDialogPrivate	qdialog_p.h	77	0xb7b82a1c	
    8	QMessageBoxPrivate	qmessagebox.cpp	143	0xb7b82a1c	
    9	QMessageBox::QMessageBox	qmessagebox.cpp	737	0xb7b82a1c	
    10	__static_initialization_and_destruction_0	mainwindow.cpp	9	0x804e3c4	
    11	_GLOBAL__sub_I_typing	mainwindow.cpp	188	0x804e424	
    12	__libc_csu_init			0x806ff52	
    13	__libc_start_main		246	0xb6fc0a1a	
    14	_start			0x804d3f1	
    

    qglobal.cpp

    
    #elif (defined(Q_OS_UNIX) || defined(Q_CC_MINGW))
            abort(); // trap; generates core dump-------->>>> this is error line
    #else
    

  • Moderators

    You said you don't have static global QObjects and then there's this:

    //mainwindow.cpp
    
    ...
    QMessageBox msg;
    ...
    

    The error points you exactly to this line and says what the error is:

    10  __static_initialization_and_destruction_0   mainwindow.cpp  9   0x804e3c4
    

    That's it. Don't make static global QObjects.

    On a side note. You don't need to keep an instance of QMessageBox. It has convenience static methods to display warnings e.g. like this:

    QMessageBox::warning(this, tr("Login failed"), msgerror, QMessageBox::Ok);
    


  • @Chris-Kawa really really thankssssss.
    How am I silly.
    So sorry. You say right. Excuse me for my poor knowledge.
    I think static object is like c#. : static int a;
    Cause of tho I said I don't have static. So sorry . Thanks boss. Really thanks.
    I love Qt.


  • Moderators

    No problem. I'm glad I could help.
    In c++ static keyword has a different meaning in class member declarations and global variables. A variable declared in global scope always has static storage duration. A static keyword on such variable refers to the linkage.

    See here for more info.
    I'd stay away from global variables, Qt or otherwise. Although they have their uses they are usually nothing but trouble.


  • Qt Champions 2016

    @Chris-Kawa
    register was deprecated in C++11?! What a boomer ...



  • @Chris thanks. and thanks all.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.