Threading in Qt
Template:Abstract 76ytuiytuityutyutututyutyutyu represents a separate thread of control within the program; it shares data with all the other threads within the process but executes independently.
Source Code[edit | edit source]
Header File[edit | edit source]
- ifndef THREAD_H
- define THREAD_H
- include <QtGui/QWidget>
- include<QThread>
- include<QPushButton>
- include<QHBoxLayout>
- include<QCloseEvent>
class thread : public QWidget
{
Q_OBJECT
public:
thread(QWidget *parent = 0);
~thread();
protected:
void closeEvent(QCloseEvent *event);
private slots:
void startOrStopThreadA();
void startOrStopThreadB();
private:
QThread threadA;
QThread threadB;
QPushButton *threadAButton;
QPushButton *threadBButton;
QPushButton *quitButton;
QHBoxLayout *lay;
};
- endif // THREAD_H
Source File[edit | edit source]
- include "thread.h"
thread::thread(QWidget *parent)
: QWidget(parent)
{
lay=new QHBoxLayout();
threadAButton = new QPushButton(tr("Start A"), this);
threadBButton = new QPushButton(tr("Start B"), this);
quitButton = new QPushButton(tr("Quit"), this);
setStyleSheet("* { background-color:rgb(190,50,88);color:rgb(255,255,255); padding: 7px}}");
quitButton->setDefault(true);
connect(threadAButton, SIGNAL(clicked()),this, SLOT(startOrStopThreadA()));
connect(threadBButton, SIGNAL(clicked()),this, SLOT(startOrStopThreadB()));
connect(quitButton, SIGNAL(clicked()),this, SLOT(close()));
lay->addWidget(threadAButton);
lay->addWidget(threadBButton);
lay->addWidget(quitButton);
setLayout(lay);
showMaximized();
}
thread::~thread()
{
// No need to delete any object that has got a parent which is properly deleted.
}
void thread::startOrStopThreadA()//this method start thread and stop the second running thread
{
if (threadA.isRunning())
{
threadA.terminate();
threadAButton->setText(tr("Start A"));
}
else
{
threadA.start();//thread A started
threadAButton->setText(tr("Stop A"));
threadB.terminate();
threadBButton->setText(tr("Start B"));
}
}
void thread::startOrStopThreadB()//this method start thread and stop the second running thread
{
if (threadB.isRunning())
{
threadB.terminate();
threadBButton->setText(tr("Start B"));
}
else
{
threadB.start();//thread B started
threadBButton->setText(tr("Stop B"));
threadA.terminate();
threadAButton->setText(tr("Start A"));
}
}
void thread::closeEvent(QCloseEvent *event)//thread termination
{
threadA.terminate();
threadB.terminate();
threadA.wait();
threadB.wait();
event->accept();
}
Screenshot[edit | edit source]
- press "start A" to start A thread and stop B thread
- press "start B" to start B thread and stop A thread
- press "quit" to terminate all threads