I'm usign a QProgressBar to know the state of a job that consist in read a file.
My problem is if during that process i click in anything or open anothers aplications, my aplication act like it crashed and just show 100% when the process finish, like: 1%, 2%, i click, ------------------ 100%.
If i just run and didn't do nothing in my pc the QProgressBar show the process correct, like, 1%, 2%, 3%, 4%, ..., 99%, 100%.

Qt Code:
  1. #ifndef MAINWINDOW_H
  2. #define MAINWINDOW_H
  3.  
  4. #include <QtGui/QMainWindow>
  5. #include <QProgressBar>
  6.  
  7. class MainWindow : public QMainWindow
  8. {
  9. Q_OBJECT
  10.  
  11. public:
  12. MainWindow(QWidget *parent = 0);
  13. ~MainWindow();
  14.  
  15. public slots:
  16. void test();
  17.  
  18. private:
  19. QProgressBar *progress;
  20. };
  21.  
  22. #endif // MAINWINDOW_H
To copy to clipboard, switch view to plain text mode 

Qt Code:
  1. #include "mainwindow.h"
  2. #include <QDebug>
  3. #include <QString>
  4. #include <QDir>
  5. #include <QFileDialog>
  6. #include <QMessageBox>
  7. #include <QLabel>
  8. #include <QProgressBar>
  9. #include <QLayout>
  10. #include <QVBoxLayout>
  11. #include <QTimer>
  12. #include <QProgressDialog>
  13.  
  14. MainWindow::MainWindow(QWidget *parent)
  15. : QMainWindow(parent)
  16. {
  17.  
  18. QVBoxLayout *layout = new QVBoxLayout;
  19. progress = new QProgressBar;
  20. layout->addWidget(progress);
  21.  
  22. QWidget *w=new QWidget();
  23. w->setLayout(layout);
  24. this->setCentralWidget(w);
  25.  
  26. QTimer::singleShot(100, this, SLOT(test()));
  27. }
  28.  
  29. MainWindow::~MainWindow()
  30. {
  31.  
  32. }
  33.  
  34. void MainWindow::test(){
  35. QString dir = QFileDialog::getOpenFileName(this, tr("Select Text File"),"",tr("Text (*.txt)"));
  36. QFile f(dir);
  37. f.open(QIODevice::ReadOnly);
  38. if(f.isOpen())
  39. {
  40. int fileSize=f.size();
  41. int step=fileSize/100;
  42. int bytesProcessed=0;
  43. QString line;
  44. progress->setMaximum(fileSize);
  45. progress->setValue(bytesProcessed);
  46. while (not f.atEnd()){
  47. line = f.readLine().data();
  48. bytesProcessed+= line.size();
  49. list = line.split(":");
  50. if (bytesProcessed%step<=20){
  51. //qDebug()<<"bytesProcessed:"<<bytesProcessed;
  52. progress->setValue(bytesProcessed);
  53. }
  54. }
  55. progress->setValue(bytesProcessed);
  56.  
  57. }
  58. else
  59. {
  60. QMessageBox::warning(this,"Error","No file selected!");
  61. }
  62. }
To copy to clipboard, switch view to plain text mode