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. (seemingly) simple Qt app: creating a progress bar
QtWS25 Last Chance

(seemingly) simple Qt app: creating a progress bar

Scheduled Pinned Locked Moved General and Desktop
72 Posts 5 Posters 58.6k 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.
  • mzimmersM Offline
    mzimmersM Offline
    mzimmers
    wrote on last edited by
    #1

    Hi, all -

    Some of you know me already: I've been using Qt as an IDE for about a year now (and love it). I've been trying to convince a reluctant management to let me begin experimenting with putting a Qt UI on a desktop app I'm building, and now have a short window of opportunity. I think I'd like to begin with something ultra simple: our program reads a data file, processes it and produces output files. I'd like to add a progress bar to help the user monitor how far through the input file the program is.

    Since my real program is way too complex to get into here, I've created a stub program that I think contains the essentials for this:

    @#include <iostream>
    #include <fstream>
    #include <string>

    using namespace std;

    long getFileSize (fstream& f)
    {
    long end;

    f.seekg (0, ios::end);
    end = f.tellg();
    f.seekg(0, ios::beg);

    return end;
    }

    int main()
    {
    long curr, end, percent;
    string myStr;
    fstream myFile("test.pro.user");

    end = getFileSize(myFile);

    while (myFile.good())
    {
    myFile >> myStr;
    curr = myFile.tellg();

    // special handling for end of file.

    if (curr != -1)
    percent = curr * 100 / end;
    else
    percent = 100;

    cout << percent << " percent finished." << endl;
    }

    myFile.close();

    return 0;
    }
    @

    So, I've been doing some reading of the docs, and (as usual) I'm a little lost in how to get started. I don't expect anyone to do this for me, but could someone point me in the right direction? I believe I want to use this:

    "Qt page on progress bar":http://developer.qt.nokia.com/doc/qt-4.8/qprogressbar.html

    ...but I'm sure there's more to it than just including this widget.

    Any guidance would be appreciated. Thanks so much.

    I've already gotten a development team across the continent to use Qt for their IDE, so my evangelism is making (slow) progress. I think if I can pull off this, and a few embellishments, they'll let me use Qt as the tool for the UI in an upcoming project with large commercial implications.

    1 Reply Last reply
    0
    • sierdzioS Offline
      sierdzioS Offline
      sierdzio
      Moderators
      wrote on last edited by
      #2

      I think you would be much better off if you start developing your app in Qt. Starting in std and then migrating to Qt is harder - especially when you are learning.

      Standard way here would be to update progress bar using signal and slot mechanism, but that would require a big rewrite of your code. For something simpler that might (I've not tested) work, try this:
      @
      #include <QApplication>
      #include <QProgressBar>

      int main()
      {
      long curr, end, percent;
      string myStr;
      fstream myFile("test.pro.user");

      end = getFileSize(myFile);

      QProgressBar bar(0);
      bar.setRange(0, 100);
      bar.setValue(0);
      bar.show();

      while (myFile.good())
      {
      myFile >> myStr;
      curr = myFile.tellg();

      // special handling for end of file.

      if (curr != -1)
      percent = curr * 100 / end;
      else
      percent = 100;

      bar.setValue(persent);

      cout << percent << " percent finished." << endl;
      }
      @

      I'm not sure it will work, I would normally have done it in a much different way. For an example app, you can take a look at my "sPDaR":https://gitorious.org/spdar/spdar/trees/master, but proceed with caution, as this is a very old and crude code :) Works, though.

      (Z(:^

      1 Reply Last reply
      0
      • G Offline
        G Offline
        goetz
        wrote on last edited by
        #3

        Be aware, that updates to the progress bar are more or less blocked as long as the while loop is running. To make the application responsible while the work is done, one could consider using a worker thread. As a workaround, one should at least run the even loop handler after changing the progress bar's values. A [[Doc:QProgressDialog]] can be an alternative too, it suffers from a non running event loop too.

        http://www.catb.org/~esr/faqs/smart-questions.html

        1 Reply Last reply
        0
        • mzimmersM Offline
          mzimmersM Offline
          mzimmers
          wrote on last edited by
          #4

          Volker: I'm not sure I understand. Are you saying that this isn't feasible?

          @while (something)
          {
          do some work
          update to reflect the progress of the work
          }
          @

          1 Reply Last reply
          0
          • G Offline
            G Offline
            goetz
            wrote on last edited by
            #5

            You can do this, but the event loop must be run regularly, so that the events (e.g. repaints, mouse events, key press event, and so on) are handled. As long as you are within the while loop, this is only done if you call QApplication::processEvents() manually. Otherwise the the application is blocked, on the Mac it usually shows the rotating, colored "beach ball" and on Windows that "this application doesn't react" message.

            http://www.catb.org/~esr/faqs/smart-questions.html

            1 Reply Last reply
            0
            • mzimmersM Offline
              mzimmersM Offline
              mzimmers
              wrote on last edited by
              #6

              OK, so if I can pursue this a bit further:

              1. the application, once started is completely compute-bound. No action from the user is needed nor permitted.
              2. in my "real" app, it executes about 750 loops per second. (I'm talking about my compute loops, not the event loops).

              But, I'm left with the impression that you don't like this idea. So, returning to the original example, what would have been a preferred design?

              Thanks.

              1 Reply Last reply
              0
              • G Offline
                G Offline
                goetz
                wrote on last edited by
                #7

                In that case I would move the actual computation to a worker thread. Use the pattern that's recommended nowadays: Create a QObject subclass that does the work and QThread as a managing helper only (no subclassing of QThread). The "Threads, Events and QObjects":/wiki/Threads_Events_QObjects wiki article has the details. Your worker object defines a signal, say progress(int value, int max) that you emit, say every 200 iterations of your loop (in every iteration it would just flood the app with events!). The main thread does little less than opening a progress bar (or progress dialog) and spins the event loop for the GUI.

                http://www.catb.org/~esr/faqs/smart-questions.html

                1 Reply Last reply
                0
                • mzimmersM Offline
                  mzimmersM Offline
                  mzimmers
                  wrote on last edited by
                  #8

                  OK...I scanned the article you identified. I was taken by this line:

                  bq. Nine times out of ten, a quick inspection of their code shows that the biggest problem is the very fact they’re using threads in the first place, and they’re falling in one of the endless pitfalls of parallel programming.

                  So...am I "doing this wrong?" I'll go this route if you think it's best, but I'm open to other suggestions (as long as they don't entail a complete re-write of my app; the boss won't go for that).

                  Back to the example I posted originally: would you (hypothetically) use threads for that as well?

                  1 Reply Last reply
                  0
                  • G Offline
                    G Offline
                    goetz
                    wrote on last edited by
                    #9

                    In your case I would say that going with multithreaded architecture is ok. That 9-of-10 statement referes to stuff where you don't need MT at all, like putting an already asynchronous API like QNAM or sockets into a thread to make it asynchronous.

                    To answer the last question: yes, I would use a thread for this.

                    http://www.catb.org/~esr/faqs/smart-questions.html

                    1 Reply Last reply
                    0
                    • mzimmersM Offline
                      mzimmersM Offline
                      mzimmers
                      wrote on last edited by
                      #10

                      OK, thanks, Volker...I guess I've got some reading to do. I appreciate the feedback, as always.

                      Edit: Volker, I sent you an email with a couple of questions; if you're so inclined to respond, that would be great.

                      1 Reply Last reply
                      0
                      • mzimmersM Offline
                        mzimmersM Offline
                        mzimmers
                        wrote on last edited by
                        #11

                        OK, I've done a little work on this. I know it's incomplete, and I'm sure it's not right yet, but...I'm ready to ask for some feedback. Thanks...

                        @#include <iostream>
                        #include <fstream>
                        #include <string>

                        using namespace std;

                        #include <QApplication>
                        #include <QProgressBar>

                        long getFileSize (fstream& f)
                        {
                        long end;

                        f.seekg (0, ios::end);
                        end = f.tellg();
                        f.seekg(0, ios::beg);

                        return end;
                        }

                        class WorkerThread : public QObject
                        {
                        Q_OBJECT
                        private:
                        fstream myFile;
                        public:
                        WorkerThread() : myFile("test.pro.user") {}

                        void run()
                        {
                        long curr, end, percent;
                        string myStr;

                        end = getFileSize(myFile);

                        while (myFile.good())
                        {
                        myFile >> myStr;
                        curr = myFile.tellg();

                        // special handling for end of file.

                        if (curr != -1)
                        percent = curr * 100 / end;
                        else
                        percent = 100;

                        // some kind of signal to be emitted here

                        cout << percent << " percent finished." << endl;
                        }
                        }
                        signals:
                        void percentChanged(int percent);
                        };

                        int main(int argc, char *argv[])
                        {
                        QApplication app (argc, argv);
                        WorkerThread worker;

                        QProgressBar bar(0);
                        bar.setRange(0, 100);
                        bar.setValue(0);
                        bar.show();
                        // bar.setValue(percent);

                        return app.exec();
                        }

                        void WorkerThread::percentChanged(int percent) {}
                        @

                        1 Reply Last reply
                        0
                        • G Offline
                          G Offline
                          goetz
                          wrote on last edited by
                          #12

                          On a first glance, that looks good. Despite the fact that you might consider using [[Doc:QFile]]/[[Doc:QTextStream]] for the file operations and [[Doc:QFileInfo]] for getting the file size (instead of your method).

                          Then you must not define the method for the signal yourself, this is done automatically by moc. It is sufficient to just declare the signal in the class header file.

                          The signal must be emitted in the run method of your thread:

                          @
                          // some kind of signal to be emitted here
                          emit percentChanged(percent);
                          @

                          You'll also have to connect that signal to the progress bar:

                          @
                          connect(worker, SIGNAL(percentChanged(int)), bar, SLOT(setValue(int)));
                          @

                          Also, the worker needs to be moved to a thread, and eventually started:

                          @
                          QProgressBar bar(0);
                          bar.setRange(0, 100);
                          bar.setValue(0);
                          bar.show();

                          WorkerThread worker;
                          QThread thread;
                          worker.moveToThread(&thread);

                          // run the run method of the worker object once the thread has started
                          connect(&thread, SIGNAL(started())), &worker, SLOT(run()));

                          // update the progress bar
                          connect(&worker, SIGNAL(percentChanged(int)), &bar, SLOT(setValue(int)));

                          thread.start();
                          @

                          to make the autostart work, you must declare WorkerThread::run() as public slot.

                          http://www.catb.org/~esr/faqs/smart-questions.html

                          1 Reply Last reply
                          0
                          • mzimmersM Offline
                            mzimmersM Offline
                            mzimmers
                            wrote on last edited by
                            #13

                            [quote author="Volker" date="1329477431"]On a first glance, that looks good. Despite the fact that you might consider using [[Doc:QFile]]/[[Doc:QTextStream]] for the file operations and [[Doc:QFileInfo]] for getting the file size (instead of your method)[/quote]

                            Good to know about those...thanks. For now, I'll just leave it as is. The plan is to:

                            get this working with a minimum of effort on my sample program

                            transfer the Qt-specific code to my simulator

                            let the powers-that-be see how cool even a bit of Qt razzle-dazzle is

                            go whole-hog on the big job that's hopefully coming up this spring

                            [quote]Then you must not define the method for the signal yourself, this is done automatically by moc. It is sufficient to just declare the signal in the class header file.[/quote]

                            Oh yeah; I knew that (sort of).

                            [quote] The signal must be emitted in the run method of your thread:

                            @
                            // some kind of signal to be emitted here
                            emit percentChanged(percent);
                            @

                            bq. You'll also have to connect that signal to the progress bar:

                            @
                            connect(worker, SIGNAL(percentChanged(int)), bar, SLOT(setValue(int)));
                            @

                            bq. Also, the worker needs to be moved to a thread, and eventually started:

                            @
                            QProgressBar bar(0);
                            bar.setRange(0, 100);
                            bar.setValue(0);
                            bar.show();

                            WorkerThread worker;
                            QThread thread;
                            worker.moveToThread(&thread);

                            // run the run method of the worker object once the thread has started
                            connect(&thread, SIGNAL(started())), &worker, SLOT(run()));

                            // update the progress bar
                            connect(&worker, SIGNAL(percentChanged(int)), &bar, SLOT(setValue(int)));

                            thread.start();
                            @

                            bq. to make the autostart work, you must declare WorkerThread::run() as public slot.[/quote]

                            Done, done and done. I'm geting a compiler error that "'connect' was not declared in this scope." I'm including QObject; isn't that where connect lives?

                            EDIT: does the connect need object context? There isn't any in the example on the signals/slots doc page.

                            1 Reply Last reply
                            0
                            • M Offline
                              M Offline
                              mlong
                              wrote on last edited by
                              #14

                              If you're using connect() outside of a class that's a subclass of QObject, you'll need to use the full name of the static method, "QObject::connect()"

                              Software Engineer
                              My views and opinions do not necessarily reflect those of anyone -- living or dead, real or fictional -- in this universe or any other similar multiverse node. Void where prohibited. Your mileage may vary. Caveat emptor.

                              1 Reply Last reply
                              0
                              • G Offline
                                G Offline
                                goetz
                                wrote on last edited by
                                #15

                                Oh, using QFile and friends is much more easier than the stdlib methods - give it a try! :)

                                As mark already mentioned, just call QObject::connect(). That method ist static in QObject, so that works without problems.

                                http://www.catb.org/~esr/faqs/smart-questions.html

                                1 Reply Last reply
                                0
                                • mzimmersM Offline
                                  mzimmersM Offline
                                  mzimmers
                                  wrote on last edited by
                                  #16

                                  [quote author="Volker" date="1329495814"]Oh, using QFile and friends is much more easier than the stdlib methods - give it a try! :) [/quote]

                                  I believe you, but...the goal for this exercise is not to show off all of Qt's programming features, but to impress upon some reluctant management that it needn't be invasive to a program's design.

                                  [quote]As mark already mentioned, just call QObject::connect(). That method ist static in QObject, so that works without problems.[/quote]

                                  Cool...that's the first time I've seen that done.

                                  OK...now I'm getting a linker error:

                                  @Undefined symbols:
                                  "vtable for WorkerThread", referenced from:
                                  WorkerThread::WorkerThread()in main.o
                                  @

                                  That doesn't look like a coding problem to me; am I missing a library or something?

                                  1 Reply Last reply
                                  0
                                  • G Offline
                                    G Offline
                                    goetz
                                    wrote on last edited by
                                    #17

                                    Some missing moc steps.

                                    I would recommend to put the WokerThread class in a separate .h header file (and probably extract the implementation to a .cpp file).

                                    moc is usually not run on the file that contains the main method.

                                    If you have changed your project, do a full rebuild to catch up for all the changes.

                                    http://www.catb.org/~esr/faqs/smart-questions.html

                                    1 Reply Last reply
                                    0
                                    • mzimmersM Offline
                                      mzimmersM Offline
                                      mzimmers
                                      wrote on last edited by
                                      #18

                                      Oh...excellent! This is very, very encouraging.

                                      EDIT:

                                      Actually, let's just get to the real thing here: this is the main routine in my application:

                                      @#include <iostream>
                                      #include <string>

                                      #include "modem.h"

                                      using namespace std;

                                      int main ()
                                      {
                                      Modem modem;
                                      bool clockEnable = HIGH;
                                      bool resetFlag = LOW;

                                      int32_t rc = 0;
                                      int32_t i = 0;

                                      while (rc == 0)
                                      {
                                      systemClock.setClock(HIGH);
                                      rc = modem.cycle(clockEnable, resetFlag);

                                      systemClock.setClock(LOW);
                                      modem.cycle(clockEnable, resetFlag); // no need to check rc on low clock

                                      if (++i % 1000 == 0)
                                      cout << "main cycled " << dec << i << " times." << endl;
                                      }

                                      return 0;
                                      }
                                      @

                                      So...do the guts of this become my run() function? And, what's currently in my example main() essentially goes into my app main()? Is that the gist of it?

                                      Also, I'd like to move as much of the progress bar processing out of main(). I know it's only three lines now, but...once I get this working in my app, I'm planning on adding some stuff to the UI. Any reason I shouldn't pursue this?

                                      Thanks...

                                      1 Reply Last reply
                                      0
                                      • G Offline
                                        G Offline
                                        goetz
                                        wrote on last edited by
                                        #19

                                        Yes, the contents of the main method would go into the worker class. Make the Modem and the flags a class variable, and the rest into the run slot. The singal and emit is just like in the dummy example we had before.

                                        [EDIT: the contents of the main method goes to the class, not the method itself, of course :) ]

                                        http://www.catb.org/~esr/faqs/smart-questions.html

                                        1 Reply Last reply
                                        0
                                        • mzimmersM Offline
                                          mzimmersM Offline
                                          mzimmers
                                          wrote on last edited by
                                          #20

                                          OK, thanks, Volker. On a related subject, I've been experimenting with creating a QMainWindow, but evidently, I don't understand the constructors as well as I thought. The line:

                                          @ QProgressBar bar(0);@

                                          Is creating an object of type QProgressBar named bar, and with no parent, right? So why doesn't this:

                                          @ QMainWindow mainWindow;
                                          QProgressBar bar(*mainWindow);
                                          @

                                          Create a QMainWindow, and then a bar whose parent is the QMainWindow? I'm getting a "no matching function" compiler error.

                                          1 Reply Last reply
                                          0

                                          • Login

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