Problem in call class in mainwindoe.cpp

  • Hi.
    I create a program for embedded ARM system. It reads data from serial port and save it in database.
    I create 2 classes ( one for data base and the other for serial port).
    The database classes is created database and tables if not exist and then will insert update data.
    Serial port classes is open port and config port and read data from port and close the port.
    When I make the classes they do not work.
    the database error show this message :

    [root@FriendlyARM /fgit]# ./TimeAttandent2 -qws -font 12
    QSqlQuery::exec: database not open
    QSqlQuery::exec: database not open

    and the readcard function does not work. (But when I put this code in mainwindow.cpp it worked )
    this is my database class : (create connection and create tables)

    #ifndef DB_H
    #define DB_H
    #include "QtSql/qsql.h"
    #include "QtSql/qsqldatabase.h"
    #include "QtSql/qsqlquery.h"
    #include "QtSql/qsqltablemodel.h"
    #include <QtCore/QDateTime>
    #include <QVariant>   //=>query.value()
    #include <QSqlRecord>
    #include <QSqlError>
    #include <csignal>
    #include <QDateTime>
    class DB
        QSqlDatabase daba;
        QString msg;
        QSqlQuery q;
        bool success;
    #endif // DB_H

    And this is DB.cpp:

    #include "db.h"
        daba = QSqlDatabase::addDatabase("QSQLITE");//not dbConnection
        QString path = "DataBase";
            msg=("Error to open database");
            msg="The Database is open sucessfully";
            //create the tables if not created.
            q.exec("create table IF NOT EXISTS Person("
                   "name varchar(20),"
                   "pid  varchar(20),"
                   "pic varchar(100),"
                   "password varchar(20),"
                   "boss varchar(10));");
            //boos if the user is manager
            q.exec("create table IF NOT EXISTS IO(record int primary key,"
                   "cf varchar(20) ,"
                   "pid varchar(20), "
                   "DateTime varchar(50));");

    I read data from serial port and save them in data base.And this is my serial port class :

    #ifndef PORTSERIAL_H
    #define PORTSERIAL_H
    #include <stdio.h>   /* Standard input/output definitions */
    #include <unistd.h>  /* UNIX standard function definitions */
    #include <fcntl.h>   /* File control definitions */
    #include "errno.h"   /* Error number definitions */
    #include "termio.h" /* POSIX terminal control definitions */
    #include <QString>
    #include <QDateTime>
    #define MAXDATASIZE 100
    class PortSerial
    public :
        int fd;
        int status;
        char buf2[MAXDATASIZE];
        QString output;
        int openport();
        int configport();
        void closeport();
        void readcard(QString &output);
    #endif // PORTSERIAL_H

    this is serial port cpp:

    #include "portserial.h"
    #include <QString>
        //inja hatman bayad khoroji ra check konin
    int PortSerial::openport()
       QString portname="/dev/ttySAC3";
       if (fd==-1)
           return -1;//return open port error
           return 1;
    void PortSerial::closeport()
    int PortSerial::configport(void)
        struct termios tty;
        struct termios tty_old;
        memset (&tty, 0, sizeof tty);
        /* Error Handling */
        if ( tcgetattr ( fd, &tty ) != 0 ) {
           //qDebug() << "Error " << errno << " from tcgetattr: " << strerror(errno) << std::endl;
            return -2;
        /* Save old tty parameters */
        tty_old = tty;
        /* Set Baud Rate */
        cfsetospeed (&tty, (speed_t)B9600);
        cfsetispeed (&tty, (speed_t)B9600);
        /* Setting other Port Stuff */
        tty.c_cflag     &=  ~PARENB;            // Make 8n1
        tty.c_cflag     &=  ~CSTOPB;
        tty.c_cflag     &=  ~CSIZE;
        tty.c_cflag     |=  CS8;
        tty.c_cflag     &=  ~CRTSCTS;           // no flow control
        tty.c_cc[VMIN]   =  1;                  // read doesn't block
        tty.c_cc[VTIME]  =  5;                  // 0.5 seconds read timeout
        tty.c_cflag     |=  CREAD | CLOCAL;     // turn on READ & ignore ctrl lines
        /* Make raw */
        /* Flush Port, then applies attributes */
        tcflush( fd, TCIFLUSH );
        if ( tcsetattr ( fd, TCSANOW, &tty ) != 0) {
           //qDebug() << "Error " << errno << " from tcsetattr" << std::endl;
            return -3;
        return 1;
    void PortSerial::readcard(QString &output)
        //QString output;//chon ham sat ham shomare kart hast ba * az ham joda mishan
        int numbytes;
        //card*sat time
            if ((numbytes = read(fd,buf2, MAXDATASIZE)) != -1)
                buf2[numbytes] = '\0';
                QString s1(buf2);
                read(fd,buf2, MAXDATASIZE-1) ;
                QString s2(buf2);
                QString card=(s1+s2);
                QString dt=QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss");

    and this is my mainwindow.h code:

    #ifndef MAINWINDOW_H
    #define MAINWINDOW_H
    #include <QMainWindow>
    #include <QSocketNotifier>
    //#include "menu.h"
    #include "db.h"
    #include "portserial.h"
    namespace Ui {
    class MainWindow;
    class MainWindow : public QMainWindow
        explicit MainWindow(QWidget *parent = 0);
        DB *database;
        PortSerial *serialport;
    //    QSocketNotifier *notifier ;
    private slots:
        void on_pushButton_clicked();
        void ReadAndProcessData();
        Ui::MainWindow *ui;
    #endif // MAINWINDOW_H

    and .cpp:

    #include "mainwindow.h"
    #include "ui_mainwindow.h"
    #include "menu.h"
    //DB *database=new DB("IODataBase");
    //PortSerial *serialport=new PortSerial();
    QSocketNotifier *notifier ;
    MainWindow::MainWindow(QWidget *parent) :
        ui(new Ui::MainWindow)
        serialport=new PortSerial();
        database=new DB();
        ui->label->setText("the status of device");
        notifier=new QSocketNotifier(serialport->fd, QSocketNotifier::Read,this);
        int a=serialport->status;
        delete ui;
    void MainWindow::on_pushButton_clicked()
        Menu *mf=new Menu();
    void MainWindow::ReadAndProcessData()
        QString st="welcome";
        QString output;
    int a=serialport->status;

  • Lifetime Qt Champion


    There's no code related to writing anything in the database so there's no real way to tell why the connection is closed.

    By the way, why not use QSerialPort ?

  • @SGaist : Thanks for reply.

    There's no code related to writing anything in the database so there's no real way to tell why the connection is closed.

    In DB.cpp in constructor class ( DB() ) , I open the database and create table. (after tested the project I saw the error that say can not open the database. I decide solve the problem at first then will write other code to update and inset)

    By the way, why not use QSerialPort ?

    For Qserial port in documentation wrote Since: Qt 5.1. I have qt-4.8. That was not worked.

    My problem is : I call my functions but they do not worked.

  • Lifetime Qt Champion

    Why did you erase your original post ?

    The qtserialport module can be build with Qt 4.8, there's a branch for it.

    Without seeing your code there's no way to tell why it doesn't work. Also "doesn't work" doesn't tell much about what is happening (or not happening for that matter). You should explain what you expect to have and what you get.

    For your database problem, at some point it's either never opened or closed before you try to write something in it. Again without seeing the related code, there's no way to help you.

  • @SGaist :

    Why did you erase your original post ?
    The qtserialport module can be build with Qt 4.8, there's a branch for it.

    Yes, you say right. I am finding this resource to use qserialport. :[]
    In this resource says :
    To use the library, add serialport to the *.pro file of your project:

    CONFIG += serialport


    QT += serialport

    but when I added CONFIG += serialport to my .pro file , these codes has error again :

    #include <QSerialPort>
    #include <QSerialPortInfo>

    My problem solved and it has a silly mistake on serialport class.
    The database class is worked but that error occurred because I should define query in each function after opening database. [] This post solved my problem.

  • Lifetime Qt Champion

    You're using Qt 4.8.7 so you have to compile/install it before you can use it. It's described in the Getting the source code part.

  • Lifetime Qt Champion

    As for the database part, re-opening the database each time is not necessarily the cleaner option since you are using a SQLite database. Unless you're in an environment that's highly hostile to your database connection, you should set it up when starting the application and only close it at the end. Thus you'll be using the default connection without the need to re-open the database each time you want to do a query.

  • Really thanks my friend. For qserial port and advice for opening database.

Log in to reply

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