4.QT中进程操作,线程操作
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 root@42.121.13.248"); ??? // process.start("ssh", QStringList() << "root@42.121.13.248" << "aa" << "bbb"); ??? // process.write("1\n", 2); ??? process.waitForFinished(); ? ??? // process.waitForFinished(); ??? qDebug() << process.readAll(); ??? // qDebug() << process.exitCode(); ? ??? return app.exec(); } |
多線程(可以通過moveToThread(QThread *)的方法指定給指定的線程)
新建項(xiàng)目T20Thread,項(xiàng)目代碼如下:
| 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>? //要開啟線程的時(shí)候需要使用頭文件<QThread> #include <QDebug> class Worker : public QObject { ??? Q_OBJECT public: ??? explicit Worker(QObject *parent = 0); ? ??? QThread _thread; ? ??? bool event(QEvent *ev) ??? { ??????? //通過QThread::currentThread()可以獲得當(dāng)前線程信息 ??????? 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(); } |
| 運(yùn)行結(jié)果:
|
?
總結(jié)
以上是生活随笔為你收集整理的4.QT中进程操作,线程操作的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 世界历史战争斯巴达克起义?
- 下一篇: 二手八个螺丝的电动车能卖多少钱?