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

(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
    #26

    Ah...after looking at the doc a bit more closely, I believe I misunderstood the text() function. It appears to be a getter, not a setter, so I can see how that wouldn't have worked. What's less clear is how I do set the text.

    Here's my calls to the bar object:

    @ bar->setRange(0, 100);
    bar->setValue(0);
    bar->move(10, 10);
    bar->setTextVisible(true);
    bar->show();
    @

    What am I missing here to get the progress text to display? Thanks.

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

      The "format property":/doc/qt-4.8/qprogressbar.html#format-prop of QProgressBar holds the text template that is displayed. Be aware that it's possible that the text is not displayed at all, e.g. in the Mac style!

      For your quit problem:
      By default, the application is not terminated once the last window has been closed. You can change this by adding the following line to your main method:

      @
      QApplication app(argc, argv);

      app.connect(&app, SIGNAL(lastWindowClosed()), &app, SLOT(quit()));
      @

      A quit button does work too, 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
        #28

        I did look at that (honestly!)...I figured that since it said:

        @The default value is "%p%".@

        ...that would mean it would show up by default. No big deal; it was more for my education anyway.

        Thanks for the info on the quit slot. I do plan on adding a "close" button; just taking on one thing at a time. Right now, I'm fighting a weird Windoze build/debug problem.

        More questions to follow soon...thanks.

        EDIT:

        Regarding the quit slot you suggested above, I now get a rather ominous message in the console window when I close the app window:

        bq. QThread: Destroyed while thread is still running

        Have I left some loose ends here? For example, am I supposed to write my own quit() to overload whatever the one supplied by QApplication does?

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

          OK, I'm back to this. I'm ready to add a "close" button. In fact, I've already added the button object using QPushButton. Before I wade into connecting this up with signals and slots, I have a couple housekeeping questions:

          1. I still am not sure I understand why the completion percentage doesn't show up in text format. The way I read the documentation, by default, "%p%" will display, and just to make sure, I added a line:

          @ bar->setFormat("%p%");
          @

          But nothing shows up.

          1. I now have a QMainWindow objects that "contains" (if that's the right term) two other objects: QProgressBar and QPushButton. Each of these objects will need some formatting code, as will (I imagine) any other objects I might add. Currently, I have a routine to configure the progress bar:

          @void configBar(QProgressBar* bar)
          {
          QString text;
          bar->setRange(0, 100);
          bar->setValue(0);
          bar->move(50, 50);
          bar->setTextVisible(true);
          bar->setFormat("%p%");
          bar->show();
          text = bar->text();
          }
          @

          As you can see, I pass it a pointer to the object as a parameter. It wouldn't seem to make sense that I'd have a separate routine for each object; is there some way to derive the "contained" objects from QMainWindow? That way, I could do all my formatting in one routine. Or, should I create my own class, with all of these objects as member elements, and access them that way?

          Thanks.

          1 Reply Last reply
          0
          • M Offline
            M Offline
            mlong
            wrote on last edited by
            #30
            1. The setFormat as written above should set the text to "0%" through "100%" as the progress bar progresses. But, as Volker said, keep in mind that text may or may not be displayed (depending on the widget style in use.) The %p is the percentage, and the trailing % is just a percent sign. %m would be used for the current step, and %v would be used for the actual value.

            2. The widgets in your mainwindow should be declared as private: member variables in the mainwindow header file. (This is basic encapsulation, so I hope I'm not saying anything too obvious to you.) Then you can have one setup routine. Traditionally (though it's a matter of style) I would something such as:

            mainwindow.h:
            @
            class MainWindow : public QMainWindow
            {
            Q_OBJECT
            ...
            void MainWindow(QWidget *parent = 0);
            ...
            private:
            void setupWidgets();

            QProgressBar *m_bar;
            QPushButton *m_button;
            // etc.
            };
            @

            and in the .cpp file:
            @
            MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent)
            {
            m_bar = new QProgressBar(this); // these are children of MainWindow
            m_button = new QPushButton(this);

            setupWidgets();
            }
            ...
            void MainWindow::setupWidgets()
            {
            // setup ProgressBar
            m_bar->setRange(0, 100);
            m_bar->setValue(0);
            m_bar->move(50, 50);
            m_bar->setTextVisible(true);
            m_bar->setFormat("%p%");
            // since calling MainWindow::show() will call show() on its children, there's no need to use m_bar->show().

            // setup PushButton
            m_button->setText("Close");

            // can also set up any appropriate signals/slots, etc. here

            }
            @
            (Brain to terminal. For illustrative purposes only.)

            I'm not sure why you're setting the "text" variable in your code above, but if you needed it somewhere else within the MainWindow class, it would be accessable via "m_bar->text()"

            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
            • mzimmersM Offline
              mzimmersM Offline
              mzimmers
              wrote on last edited by
              #31

              Thanks for the clarification on #2 above. I was only putting text in the button as a convenience; I'll probably do it as you suggest above.

              I still don't get this:

              bq. But, as Volker said, keep in mind that text may or may not be displayed (depending on the widget style in use.)

              What is this widget style you're talking about? Do I have control over it?

              Thanks.

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

                Mlong -

                I've begun re-coding based on your suggestion above. It presents an issue, though. If I create objects (like m_bar) as private members of another object (like mainWindow), then this line of code obviously doesn't work:

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

                So, is the solution to define a slot within mainWindow, and somehow re-deliver the signal to m_bar? Or, does Qt offer a somewhat more automated way of accomplishing this?

                Thanks.

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

                  bq. What is this widget style you’re talking about? Do I have control over it?

                  On a Mac, Qt draws widgets in a Mac style. On Windows, it uses Windows' style. And so on. There are a number of ways to override the default style (although not all styles are available on all platforms -- you can't have Mac-styled widgets on Windows, for instance.) See "here":http://developer.qt.nokia.com/doc/qt-4.8/style-reference.html for some more details.

                  bq. So, is the solution to define a slot within mainWindow, and somehow re-deliver the signal to m_bar?

                  That's probably the most straightforward way I can think of offhand. Just create a public slot in MainWindow that will pass the information on to m_bar. That way you just expose the functionality that the world outside your widget needs to have access to, rather than exposing the entire QProgressBar. It makes the interface to your MainWindow class a little more tidy, in that it can have an interface to the outside world that is directly-related to the business at hand.

                  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
                  • mzimmersM Offline
                    mzimmersM Offline
                    mzimmers
                    wrote on last edited by
                    #34

                    Thanks for the clarification about styles. It makes sense, now...it explains why Qt applications don't look identical on all platforms.

                    I took a stab at changing the signal to go to the mainWindow object. It compiles, but doesn't work:

                    in main.cpp, the new connect looks like:

                    @ QObject::connect(&worker,
                    SIGNAL(percentChanged(int)),
                    &mainWindow,
                    SLOT(setBarValue(int)));
                    @

                    and in mainwindow.cpp, I believe I need something like:

                    @void MainWindow::setBarValue(int i)
                    {
                    emit barValueChanged(i);
                    }
                    @

                    But I'm not sure where to go from here. Do I need another connect() call, and/or do I implement another slot to handle this signal, or...not?

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

                      No, in the slot setBarValue(), you call

                      @
                      void MainWindow::setBarValue(int i)
                      {
                      m_bar->setValue(i);
                      }
                      @

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

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

                        Oh, yes...because QProgressBar already has the smarts to know what to do with this, right? Got it. Thanks, Volker.

                        OK, I guess the next step is to empower the close button. (Then maybe a start/stop button, and that'll be that for this exercise.) I gather that I'm probably to use this signal:

                        @void QAbstractButton::clicked ( bool checked = false ) [signal]@

                        Assuming this is right:

                        1. would the connect() call most appropriately go within the MainWindow constructor?
                        2. I gather the first half of the connect() would look like this:

                        @ connect(&m_button, SIGNAL(clicked(bool)), )
                        @

                        but what would be the object for the third parameter? And, what is the signal to QMainWindow to get it to close? I can't find anything in the doc about closing (except in the saveState() method, which I'm pretty sure isn't relevant to this).

                        Thanks for the help.

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

                          The quick and dirty option would be:

                          @
                          connect(m_button, SIGNAL(clicked()), qApp, SLOT(quit()));
                          @

                          This just terminates the QApplication object, which in turn shuts down the rest of your application. Note that the bool parameter is not necessary here. It's sufficient to know that the button was clicked.

                          This is quite "rude", though, as it does not ask the user, if it was ok to quit the application and the worker thread doesn't get a chance to finish its work cleanly. So what you could do, is connect the signal to a slot in the main window class, ask the user if he/she really wants to quit the application (using one of the static [[Doc:QMessageBox]] methods). If yes, send the thread a signal to terminate its work, wait until the thread has finished (using wait, probably with a timeout). Some outline would be:

                          @
                          // move the thread and the worker out of the main method
                          // to the MainWindow class

                          // so you have
                          QThread *m_thread;
                          Worker *m_worker;

                          // define a signal
                          requestWorkerToFinish();

                          // in constructor of MainWindow:
                          connect(m_button, SIGNAL(clicked()), this, SLOT(onQuitButtonClicked()));
                          connect(this, SIGNAL(requestWorkerToFinish()), m_worker, SLOT(requestFinish()));

                          // you have to implement requestFinish in the worker!

                          void MainWindow::onQuitButtonClicked()
                          {
                          QMessageBox::StandardButton answer = QMessageBox::question(
                          this,
                          tr("Quit applicaton?"),
                          tr("Do you really want to quit the application?"),
                          QMessageBox::Yes | QMessageBox::No,
                          QMessageBox::No
                          );

                          if(answer == QMessageBox::No)
                              // user clicked no, so just continue as if nothing had happened
                              return;
                          
                          emit requestWorkerToFinish(); // no direct call!
                          bool finishOk = m_thread->wait(30000);
                          if(!finishOk) {
                              qDebug() << "WARNING: request to finish thread timed out!";
                              m_thread->terminate();
                              m_thread->wait();
                          }
                          close();
                          

                          }
                          @

                          This is brain to terminal and untested. Please expect errors :-)

                          Just a hint: if you do like outlined here, don't forget to reimplement closeEvent() in the main window. Otherwise your users are able to just nuke off your application by clicking on the (X) button in the title bar of the window!

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

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

                            Hi, Volker -

                            Since I'm not exactly breezing through this stuff, I'd like to take it step by step, so I'll begin with the quick and dirty option.

                            1. Just to keep my example program consistent with the code snippets in this thread, I tried renaming my QApplication from app to qApp. The build objected, claiming:

                            bq. error: no matching function for call to 'QApplication::QApplication(QApplication*)

                            I searched the docs for "qApp" and found that it's a global pointer, so evidently I shouldn't have tried to use it as a variable name. So, I reverted to the original variable name.

                            1. from what context (function) should the above connect call be made? If I do it in the mainwindow c'tor, it doesn't "see" my QApplication object (which lives in main()).

                            I suspect that the answers to these two issues are related. Can you tell me what's going on here? Should my QApplication object be global or something?

                            I can post code if desired. Thanks.

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

                              The purpose of the qApp macro is to provide a global access point to your QApplication. It's equivalent to the static method QCoreApplication::instance().

                              So long as you #include <QApplication> in a piece of code, then qApp will provide you with global access to your application instance.

                              Edit to add:

                              QCoreApplication (and, as such, QApplication) is an example of the "Singleton pattern.":http://en.wikipedia.org/wiki/Singleton_pattern As such, it inherently has global qualities.

                              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
                              • mzimmersM Offline
                                mzimmersM Offline
                                mzimmers
                                wrote on last edited by
                                #40

                                Well, then...I'm doing something wrong. Here's a couple of code snippets:

                                main.cpp:
                                @#include <iostream>

                                #include <QObject>
                                #include <QApplication>
                                #include <QString>
                                #include <QThread>

                                #include "workerthread.h"
                                #include "mainwindow.h"

                                using namespace std;

                                int main(int argc, char *argv[])
                                {
                                QApplication app (argc, argv);
                                MainWindow mainWindow;
                                .
                                .
                                .@

                                and mainwindow.cpp:
                                @#include <QApplication>

                                #include "mainwindow.h"

                                MainWindow::MainWindow(QWidget *parent) :
                                QMainWindow(parent)
                                {
                                m_bar = new QProgressBar (this);
                                m_button = new QPushButton (this);

                                setupWidgets();

                                connect(&m_button, SIGNAL(clicked()), app, SLOT(quit()));
                                }
                                .
                                .
                                .
                                @

                                I'm getting a compiler error that app isn't declared in mainwindow.

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

                                  bq. I’m getting a compiler error that app isn’t declared in mainwindow.

                                  It's not. The variable name "app" in main() has no bearing. It's not really a global. That's why you use qApp in other parts of your program. It's a shortcut that always refers back to "The QApplication" (There can only be one QApplication in your program, so it always "knows" what you're talking about.)

                                  @
                                  connect(&m_button, SIGNAL(clicked()), qApp, SLOT(quit()));
                                  @

                                  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
                                  • mzimmersM Offline
                                    mzimmersM Offline
                                    mzimmers
                                    wrote on last edited by
                                    #42

                                    Ahh...I suppose I should have figured that out. Thanks, mlong. Just for keeping the thread "good," I should point out another error in my code:
                                    @ connect(&m_button, SIGNAL(clicked()), qApp, SLOT(quit()));
                                    @
                                    should actually be:
                                    @ connect(m_button, SIGNAL(clicked()), qApp, SLOT(quit()));
                                    @

                                    As m_button is a pointer.

                                    Anyway...it works! (Yes, I'm excited...I've learn to measure progress in small increments with respect to my education in Qt.) So...now that the "rude" implementation works, I'm ready to start on the more "polite" version that Volker implemented above. I'll be back with more newbie questions.

                                    Thanks, mlong.

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

                                      Ah, good catch! You're right.

                                      Glad to help out!

                                      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
                                      • mzimmersM Offline
                                        mzimmersM Offline
                                        mzimmers
                                        wrote on last edited by
                                        #44

                                        Hi, Volker:

                                        Regarding this line:

                                        @connect(this, SIGNAL(requestWorkerToFinish()), m_worker, SLOT(requestFinish()));
                                        @

                                        According to the docs, requestFinish() is a signal, not a slot. Or...am I supposed to define my own slot by this name?

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

                                          requestFinish() is only a signal in class [[Doc:QHttp]] - unless exactly that is your worker, you will need to define that slot in your worker class and act accordingly (e.g. setting a bool variable to true and check that regularly in your loop in order to finish it prematurely).

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

                                          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