Hi,
i wrote a simple program, that queries the COM port. GUI specifies the data, that is sent to port, and displays the data it receives. so, my code looks like this:
/* main.cpp */
#include <QtGui/QApplication>
#include "mainwindow.h"
#include "Thread.h"
int main(int argc, char *argv[]) {
MainWindow window;
Thread thread;
QObject::connect(&thread,
SIGNAL(update
(int)),
&window,
SLOT(update
(int)));
thread.start();
window.show();
int status = app.exec();
thread.stop();
thread.wait(1000);
return status;
}
/* main.cpp */
#include <QtGui/QApplication>
#include "mainwindow.h"
#include "Thread.h"
int main(int argc, char *argv[]) {
QApplication app(argc, argv);
MainWindow window;
Thread thread;
QObject::connect(&thread, SIGNAL(update(int)), &window, SLOT(update(int)));
thread.start();
window.show();
int status = app.exec();
thread.stop();
thread.wait(1000);
return status;
}
To copy to clipboard, switch view to plain text mode
/* Thread.h */
#include <QThread>
#include <QTimer>
{
Q_OBJECT
public:
Thread();
void run();
signals:
void update(int);
public slots:
void stop();
void doAction();
private:
};
/* Thread.h */
#include <QThread>
#include <QTimer>
class Thread : public QThread
{
Q_OBJECT
public:
Thread();
void run();
signals:
void update(int);
public slots:
void stop();
void doAction();
private:
QTimer timer;
};
To copy to clipboard, switch view to plain text mode
/* Thread.cpp */
#include "Thread.h"
Thread::Thread() {
timer.setInterval(1000);
connect(&timer, SIGNAL(timeout()), this, SLOT(doAction()));
connect(this, SIGNAL(started()), &timer, SLOT(start()));
}
void Thread::run() {
exec();
}
void Thread::stop() {
timer.stop();
this->quit();
}
void Thread::doAction() {
here i write some data to port and then get some data
emit update(some data);
}
/* Thread.cpp */
#include "Thread.h"
Thread::Thread() {
timer.setInterval(1000);
connect(&timer, SIGNAL(timeout()), this, SLOT(doAction()));
connect(this, SIGNAL(started()), &timer, SLOT(start()));
}
void Thread::run() {
exec();
}
void Thread::stop() {
timer.stop();
this->quit();
}
void Thread::doAction() {
here i write some data to port and then get some data
emit update(some data);
}
To copy to clipboard, switch view to plain text mode
MainWindow is a simple window, that has a slot update.
So, the problem is that, when port is unavailable or doesn't return data, thread is trying to obtain data for several times. This operation lasts for a second and my GUI freezes for this time. I've read a nuber of books and it seems to me that my code doesn't differ from that given in the examples. Also, i haven't got this problem when i don't use event loop in my thread that is when i use msleep and while statement in QThread::run() function.
So, could anyone explain me what's wrong with my code and how could i solve this problem.
Thanks in advance.
Bookmarks