4.QT中进程操作,线程操作


  1. QT中的线程操作

T19Process.pro

SOURCES += \

    main.cpp

 

CONFIG += C++11

main.cpp

#include <QCoreApplication>
#include <QProcess>
#include <QDebug>
int main(int argc, char** argv)
{
    QCoreApplication app(argc, argv);
 
    QProcess process;
    // process.start("/home/xuegl/T0718/build-T18Database-Desktop-Debug/T18Database");
    process.start("ssh [email protected]");
    // process.start("ssh", QStringList() << "[email protected]" << "aa" << "bbb");
    // process.write("1\n", 2);
    process.waitForFinished();
 
    // process.waitForFinished();
    qDebug() << process.readAll();
    // qDebug() << process.exitCode();
 
    return app.exec();
}
  1. 多线程(可以通过moveToThread(QThread *)的方法指定给指定的线程

新建项目T20Thread,项目代码如下:

T20Thread.pro

HEADERS += \

    Worker.h \

    MyThread.h

 

SOURCES += \

    Worker.cpp \

    MyThread.cpp \

    main.cpp

Worker.h

#ifndef WORKER_H

#define WORKER_H

 

#include <QObject>

#include <QThread>  //要开启线程的时候需要使用头文件<QThread>

#include <QDebug>

class Worker : public QObject

{

    Q_OBJECT

public:

    explicit Worker(QObject *parent = 0);

 

    QThread _thread;

 

    bool event(QEvent *ev)

    {

        //通过QThread::currentThread()可以获得当前线程信息

        qDebug() << "event:" << QThread::currentThread();

        return QObject::event(ev);

    }

signals:

 

public slots:

    void doWork()

    {

        qDebug() << QThread::currentThread();

    }

};

 

#endif // WORKER_H

Worker.cpp

#include "Worker.h"

 

Worker::Worker(QObject *parent) :

    QObject(parent)

{

    //this->moveToThread(&_thread);

    _thread.start();

    connect(&_thread, SIGNAL(finished()), this, SLOT(deleteLater()));

}

MyThread.h

#ifndef MYTHREAD_H

#define MYTHREAD_H

 

#include <QThread>

#include <QDebug>

class MyThread : public QThread

{

    Q_OBJECT

public:

    explicit MyThread(QObject *parent = 0);

 

    void foo()

    {

        qDebug() << QThread::currentThread();

    }

 

    void run()

    {

        foo();

        qDebug() << "thread is run";

    }

 

signals:

 

public slots:

 

};

 

#endif // MYTHREAD_H

MyThread.cpp

#include "mythread.h"

 

MyThread::MyThread(QObject *parent) :

    QThread(parent)

{

}

main.cpp

#include <QCoreApplication>

#include "mythread.h"

#include "worker.h"

#include <QTimer>

int main(int argc, char* argv[])

{

    QCoreApplication app(argc, argv);

#if 0

    MyThread thread;

    thread.start();

 

    thread.foo();

#endif

 

    qDebug() << "main thread is"<<QThread::currentThread();

    Worker* worker = new Worker();

    QTimer* timer = new QTimer;

    //worker->moveToThread(&thread);

 

    QObject::connect(timer, SIGNAL(timeout()), worker, SLOT(doWork()));

    timer->setInterval(1000);

    timer->start();

 

    return app.exec();

}

运行结果:

4.QT中进程操作,线程操作_第1张图片

 

你可能感兴趣的:(4.QT中进程操作,线程操作)