Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • Users
  • Groups
  • Search
  • Get Qt Extensions
  • Unsolved
Collapse
Brand Logo
  1. Home
  2. Qt Development
  3. General and Desktop
  4. Using QTimer in main

Using QTimer in main

Scheduled Pinned Locked Moved Unsolved General and Desktop
11 Posts 5 Posters 1.7k Views
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • M Offline
    M Offline
    Mogli123
    wrote on last edited by aha_1980
    #1

    Hi,

    I'm new in Qt and c++ and have following problem.

    I have a databas and the data from it I show with an QTableView.
    That works so far.
    Now I want test if the QTableView update the not constant data.
    I tried to realize it with a timer but I make something wrong.

    static int zaehlerFunktion(int testWert)
    {
        testWert ++;
        return testWert;
    }
    
    
    int main(int argc, char *argv[])
    {
    
        QApplication a(argc, argv);
    
    int testwert = 10;
        QTimer timer;
        QObject::connect(&timer, &QTimer::timeout, zaehlerFunktion(testwert));
        timer.start(1000);
        TableCustomiseToolChange [2] = testwert;
    
    

    that is my error code

    0_1540971223603_für_qtforum.PNG

    I hope someone can help me.

    regards mogli

    raven-worxR 1 Reply Last reply
    0
    • M Mogli123

      Hi,

      I'm new in Qt and c++ and have following problem.

      I have a databas and the data from it I show with an QTableView.
      That works so far.
      Now I want test if the QTableView update the not constant data.
      I tried to realize it with a timer but I make something wrong.

      static int zaehlerFunktion(int testWert)
      {
          testWert ++;
          return testWert;
      }
      
      
      int main(int argc, char *argv[])
      {
      
          QApplication a(argc, argv);
      
      int testwert = 10;
          QTimer timer;
          QObject::connect(&timer, &QTimer::timeout, zaehlerFunktion(testwert));
          timer.start(1000);
          TableCustomiseToolChange [2] = testwert;
      
      

      that is my error code

      0_1540971223603_für_qtforum.PNG

      I hope someone can help me.

      regards mogli

      raven-worxR Offline
      raven-worxR Offline
      raven-worx
      Moderators
      wrote on last edited by
      #2

      @Mogli123

      1. your counting method will always return 11. You would need to change it to static int zaehlerFunktion(int& testWert)
      2. the connect statement is wrong. Do something like this:
      QObject::connect(&timer, &QTimer::timeout, [&testwert]() {
          zaehlerFunktion(testwert);
      });
      

      --- SUPPORT REQUESTS VIA CHAT WILL BE IGNORED ---
      If you have a question please use the forum so others can benefit from the solution in the future

      1 Reply Last reply
      3
      • M Offline
        M Offline
        Mogli123
        wrote on last edited by Mogli123
        #3

        Thank you now it compiles :).

        But the tableview isn't updating :(.
        How can I solve this problem?
        I thought this works automatically.

        sorry if this is basic.

        regards mogli

        JonBJ raven-worxR 2 Replies Last reply
        0
        • M Mogli123

          Thank you now it compiles :).

          But the tableview isn't updating :(.
          How can I solve this problem?
          I thought this works automatically.

          sorry if this is basic.

          regards mogli

          JonBJ Offline
          JonBJ Offline
          JonB
          wrote on last edited by
          #4

          @Mogli123
          From the 10-odd lines of code you have pasted, how can we possibly know what your code is doing?

          1 Reply Last reply
          0
          • M Mogli123

            Thank you now it compiles :).

            But the tableview isn't updating :(.
            How can I solve this problem?
            I thought this works automatically.

            sorry if this is basic.

            regards mogli

            raven-worxR Offline
            raven-worxR Offline
            raven-worx
            Moderators
            wrote on last edited by
            #5

            @Mogli123 said in Using QTimer in main:

            But the tableview isn't updating :(.
            How can I solve this problem.
            I thought this works automatically.

            what is TableCustomiseToolChange ??

            --- SUPPORT REQUESTS VIA CHAT WILL BE IGNORED ---
            If you have a question please use the forum so others can benefit from the solution in the future

            1 Reply Last reply
            0
            • M Offline
              M Offline
              Mogli123
              wrote on last edited by Mogli123
              #6

              Sorry you are right .

              (it is enough if the table is updating all 10 seconds)

              Here is my code.

              main.cpp

              static int zaehlerFunktion(int& testWert)
              {
                  testWert ++;
                  return testWert;
                  qDebug()<<"Hallo Testwert"<<testWert;
              }
              
              int main(int argc, char *argv[])
              {
              
                  QApplication a(argc, argv);
              
                  QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
                  db.setDatabaseName(":memory:");
                  if (!db.open()) {
                      QMessageBox::critical(nullptr, QObject::tr("Cannot open database"),
                          QObject::tr("Unable to establish a database connection.\n"
                                      "This example needs SQLite support. Please read "
                                      "the Qt SQL driver documentation for information how "
                                      "to build it.\n\n"
                                      "Click Cancel to exit."), QMessageBox::Cancel);
                      return false;
                  }
              
                  qint32 TableCustomiseToolChange[30];
                  int lengthTableCustomiseToolChange = 30;
                  for (int i = 0; i < lengthTableCustomiseToolChange; i++)
                  {
                      int randInt = rand() % (1010000 - 0) + 1000000;
                      TableCustomiseToolChange[i] = randInt;
              
                  }
              int testwert = 10;
                  QTimer timer;
                  QObject::connect(&timer, &QTimer::timeout, [&testwert]()
                  {
                      zaehlerFunktion(testwert);
                  });
              
                  timer.start(1000);
                  TableCustomiseToolChange [1] = testwert;
              
                  //forschleife fült Datenbank
                  QSqlQuery query;
                  query.exec("Create Table CustomiseToolChange (COLOR varchar(20),"
                                             "TOOLNR int primary key, TIME int, POCKETSTATUS varchar(20))");
                  for (int i = 0; i < (lengthTableCustomiseToolChange / 3); i++)
                  {
                      query.prepare("INSERT INTO CustomiseToolChange (COLOR, TOOLNR, TIME, POCKETSTATUS) "
                                    "VALUES (:COLOR, :TOOLNR, :TIME, :POCKETSTATUS)");
                      query.bindValue(":COLOR", "");
                      query.bindValue(":TOOLNR", TableCustomiseToolChange[i * 3 + 0]);
                      query.bindValue(":TIME", TableCustomiseToolChange[i * 3 + 1]);
                      query.bindValue(":POCKETSTATUS", TableCustomiseToolChange[i * 3 + 2]);
                      query.exec();
                   }
              
              ...
              
              

              test_screen.cpp

              test_screen::test_screen(QWidget *parent) :
                  QMainWindow(parent),
                  ui(new Ui::test_screen)
              {
                  ui->setupUi(this);
              
                  myTableCustomiseToolChange = new TableCustomise(this);
                  myTableCustomiseToolChange->setQuery("SELECT * FROM CustomiseToolChange");
                  myTableCustomiseToolChange->setHeaderData(1, Qt::Horizontal, tr("Werkzeug Nr."));
                  myTableCustomiseToolChange->setHeaderData(2, Qt::Horizontal, tr("Zeit (hh:mm:ss)\n / Teile"));
                  
                  ui->TableCustomiseToolChange->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
                  ui->TableCustomiseToolChange->setModel(myTableCustomiseToolChange);
                  ui->TableCustomiseToolChange->setColumnHidden(0, true);
                  ui->TableCustomiseToolChange->setColumnHidden(3, true);
                  ui->TableCustomiseToolChange->verticalHeader()->hide();
                  ui->TableCustomiseToolChange->setStyleSheet("QHeaderView::section { background-color:grey }");
                  ui->TableCustomiseToolChange->setStyleSheet("border: 2px solid black; background: grey");
                  ui->TableCustomiseToolChange->setSelectionMode(QAbstractItemView::NoSelection);
              
              ...
              

              tableCustomise.cpp

              TableCustomise::TableCustomise(QObject *parent)
                  : QSqlQueryModel(parent)
              {
              }
              
              QVariant TableCustomise::data(const QModelIndex &index, int role) const
              {
                  if(role == Qt::TextAlignmentRole)
                  {
                      return Qt::AlignCenter;
                  }
              
                  if (role == Qt::DisplayRole)
                  {
                      if (index.column() == 0)
                      {
                          return displayData(index, 40);
                      }
              qint32 contentForTime = index.sibling(index.row(), index.column()).data(Qt::EditRole).toInt();
                      if (index.column() == 2 && contentForTime >= 1000000)
                      {
                          return setTimeFormat(index);
                      }
                  }
                  if(role == Qt::BackgroundRole)
                  {
                      return backgroundData(index);
                  }
                  return QSqlQueryModel::data(index, role);
              }
              
              ////////////////
              QVariant TableCustomise::displayData(const QModelIndex &index, qint32 limit)const
              {
                  qint32 contentForVerificationStatus = index.sibling(index.row(), index.column() + 3).data(Qt::EditRole).toInt();
                  qint32 contentForColor = index.sibling(index.row(), index.column() + 2).data(Qt::EditRole).toInt();
              
                          if (index.column() == 0)
                          {
                              if ((limit <= contentForColor   &&  contentForColor < 1000000) || (contentForVerificationStatus == 1))
                              {
                                  return "green";
                              }
                              else if (0 < contentForColor && contentForColor <limit)
                              {
                                  return "yellow";
                              }
                              else if (contentForColor == 0 || contentForColor > 1000000)
                              {
                                  return "red";
                              }
                                          else
                              {
                                  return "yellow";
                              }
                          }
              }
              
              
              QVariant TableCustomise::backgroundData(const QModelIndex &index)const
              {
              
                  QString content = index.sibling(index.row(), 0).data(Qt::DisplayRole).toString();
                      if ( content == "red" )
                      {
                          return QBrush(Qt::red);
                      }
                      else if (content == "yellow")
                      {
                         return QBrush(Qt::yellow);
                      }
                      else if (content == "green")
                      {
                          return QBrush(Qt::green);
                      }
                      else
                      {
                          return QBrush(Qt::magenta);
                      }
              }
              
              
              QString TableCustomise::setTimeFormat(const QModelIndex &index)const
              {
                  qint32 contentForTime = index.sibling(index.row(), index.column()).data(Qt::EditRole).toInt();
              
                  if (index.column() == 2 && contentForTime >= 1000000)
                  {
                      QString formattedTime;
                      QString formattedTime_2;
                      qint32 time = contentForTime - 1000000;
                      int h = time/(60*60);
                      int min = ((time - h * (60 * 60)) / 60);
                      int sec = time % 60;
              
                      formattedTime.append(QString("%1").arg(h,2,10,QLatin1Char('0')) + ":" +
                                           QString("%1").arg(min,2,10,QLatin1Char('0')) + ":" +
                                           QString("%1").arg(sec,2,10,QLatin1Char('0')));
              
                      return formattedTime;
                   }
              }
              
              
              
              
              1 Reply Last reply
              0
              • ValentinMicheletV Offline
                ValentinMicheletV Offline
                ValentinMichelet
                wrote on last edited by
                #7

                What JonB tried to ask awkwardly is "Please could you give us more code so we can understand where the problem happens? We need for instance to know what the TableCustomiseToolChange is, where it is created and so on."

                Sometimes it's hard to know what is really relevant, because pasting your whole project is not an option, yet only pasting some random lines of your code leads people to ask more questions than they should, bother them, and make some of them not willing to investigate and answer you. Rule of thumb: have a minimal complete example of your problem, and copy paste it. The other part of code interfering and causing your problem growing exponentially (at least) with the number of lines of code. Maybe study posts on several forum (this one, Stackoverflow, QtCenter...) to understand what a good snippet is.

                Also, regarding your problem, keep in mind that doing stuff before executing the application might result in odd behavior, for the main UI loop is not yet started.

                1 Reply Last reply
                4
                • SGaistS Offline
                  SGaistS Offline
                  SGaist
                  Lifetime Qt Champion
                  wrote on last edited by
                  #8

                  Hi,

                  So basically, you would like to update the SQL table every ten seconds using the value returned by zaehlerFunktion , correct ?

                  Interested in AI ? www.idiap.ch
                  Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

                  M 1 Reply Last reply
                  1
                  • SGaistS SGaist

                    Hi,

                    So basically, you would like to update the SQL table every ten seconds using the value returned by zaehlerFunktion , correct ?

                    M Offline
                    M Offline
                    Mogli123
                    wrote on last edited by
                    #9

                    @SGaist

                    yes exactly

                    The timer is only for testing. If it works later the data change automatically, because this will be data informations from an machine.

                    1 Reply Last reply
                    0
                    • M Offline
                      M Offline
                      Mogli123
                      wrote on last edited by
                      #10

                      I have changed my code like this

                      cpp

                      test_screen::test_screen(QWidget *parent) :
                          QMainWindow(parent),
                          ui(new Ui::test_screen)
                      {
                          ui->setupUi(this);
                      
                          timer = new QTimer(this);
                          timer->setInterval(100);
                          timer->start();
                      
                          QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
                          db.setDatabaseName(":memory:");
                          if (!db.open()) {
                              QMessageBox::critical(nullptr, QObject::tr("Cannot open database"),
                                  QObject::tr("Unable to establish a database connection.\n"
                                              "This example needs SQLite support. Please read "
                                              "the Qt SQL driver documentation for information how "
                                              "to build it.\n\n"
                                              "Click Cancel to exit."), QMessageBox::Cancel);
                              return;
                          }
                      
                      
                          qint32 testwerteFuerArray[30];
                          int lengthTableCustomiseToolChange = 30;
                          for (int i = 0; i < lengthTableCustomiseToolChange; i++)
                          {
                              int randInt = rand() % (1010000 - 0) + 1000000;
                              testwerteFuerArray[i] = randInt;
                          }
                      
                      
                          functionFuerTestwert();
                      
                          connect(timer, SIGNAL(timeout()), this, SLOT(functionFuerTestwert()));
                          connect(timer, SIGNAL(timeout()), this, SLOT(fillDatabaseTableCustomiseToolChange()));
                      
                          fillArray(testwerteFuerArray, 30);
                      
                          query = new QSqlQuery;
                          query->exec("Create Table CustomiseToolChange (COLOR varchar(20),"
                                     "TOOLNR int primary key, TIME int, POCKETSTATUS varchar(20))");
                          query->prepare("INSERT INTO CustomiseToolChange (COLOR, TOOLNR, TIME, POCKETSTATUS) "
                                            "VALUES (:COLOR, :TOOLNR, :TIME, :POCKETSTATUS)");
                          query->bindValue(":COLOR", "");
                          fillDatabaseTableCustomiseToolChange();
                      
                          myTableCustomiseToolChange = new TableCustomise(this);
                          myTableCustomiseToolChange->setQuery("SELECT * FROM CustomiseToolChange");
                          myTableCustomiseToolChange->setHeaderData(1, Qt::Horizontal, tr("Werkzeug Nr."));
                          myTableCustomiseToolChange->setHeaderData(2, Qt::Horizontal, tr("Zeit (hh:mm:ss)\n / Teile"));
                      
                          ui->TableCustomiseToolChange->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
                      
                      //that doasn't work
                         connect(timer, SIGNAL(timeout()), ui->TableCustomiseToolChange, SLOT(setModel(myTableCustomiseToolChange)));
                      
                          ui->TableCustomiseToolChange->setModel(myTableCustomiseToolChange);
                      ...
                      
                      methods
                      
                      void test_screen::fillArray(qint32 valuesForCustomiseToolChangeArray[],int arrayLength)
                      {
                          for (int i=0; i<arrayLength; i++)
                          {
                              arrayCustomiseToolChange[i] = valuesForCustomiseToolChangeArray[i];
                          }
                          arrayCustomiseToolChange[1] = 10;
                      }
                      
                      void test_screen::fillDatabaseTableCustomiseToolChange()
                      {
                          for (int i = 0; i < (30 / 3); i++)
                          {
                              query->bindValue(":TOOLNR", arrayCustomiseToolChange[i * 3 + 0]);
                              query->bindValue(":TIME", arrayCustomiseToolChange[i * 3 + 1]);
                              query->bindValue(":POCKETSTATUS", arrayCustomiseToolChange[i * 3 + 2]);
                              query->exec();
                           }
                          qDebug()<<"arrayCustomiseToolChange[1] ="<<arrayCustomiseToolChange[1];
                      
                      }
                      
                      void test_screen::functionFuerTestwert()
                      {
                          arrayCustomiseToolChange[1] ++;
                      
                      }
                      

                      the array arrayCustomiseToolChange[1] ++;increases, but in the tableview nothing happend
                      what can I do that it increases the value in the table too?

                      I tried it like this connect(timer, SIGNAL(timeout()), ui->TableCustomiseToolChange, SLOT(setModel(myTableCustomiseToolChange)));
                      but it seems that this is false

                      I hope someone can help me.

                      regards mogli

                      1 Reply Last reply
                      0
                      • SGaistS Offline
                        SGaistS Offline
                        SGaist
                        Lifetime Qt Champion
                        wrote on last edited by
                        #11

                        You should always check the return value of exec and print the error if it fails.

                        Also, QSqlQuery usage pattern is on the stack not on the heap. See the Approaches to Binding Values from QSqlQuery's documentation.

                        Interested in AI ? www.idiap.ch
                        Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

                        1 Reply Last reply
                        1

                        • Login

                        • Login or register to search.
                        • First post
                          Last post
                        0
                        • Categories
                        • Recent
                        • Tags
                        • Popular
                        • Users
                        • Groups
                        • Search
                        • Get Qt Extensions
                        • Unsolved