QT程序中的事件機制是通過SIGNAL-SLOT(信號-槽)來實現的,創建一個信號與槽的連接就是使用connect方法,它是QObject類下面的一個靜態方法。在非QObject派生類中使用connect方法需要指定QObject類,即使用QObject::connect()。
環境
IDE:Qt creator 4.11.0
編譯器:MinGW 5.3.0 32bit for C++
問題
在非QObject派生類中,如何調用connect?下面是一個網上找到的例子。
例子
1、MyThread.h文件
#ifndef MYTHREAD_H
#define MYTHREAD_H
#include <QObject>
#include <QThread>
class MyThread : public QThread
{
Q_OBJECT
public:
explicit MyThread(QObject *parent = 0);
protected:
void run();
};
#endif // MYTHREAD_H
2、MyThread.cpp
#include "MyThread.h"
#include <string>
#include <iostream>
using namespace std;
MyThread::MyThread(QObject *parent) : QThread(parent)
{
}
void MyThread::run()
{
const char *pszTip = "Press 'Q' exit application.\n";
printf("%s\n", pszTip);
while (true)
{
std::string line;
std::cin >> line;
std::cout << line << std::endl;
printf("%s", pszTip);
if (line.compare("Q") == 0)
{
break;
}
}
printf("Done.");
}
3、main.cpp
#include <QCoreApplication>
#include <QDebug>
#include <QObject>
#include <QThread>
#include <string>
#include <iostream>
#include "mythread.h"
using namespace std;
int main(int argc, char *argv[])
{
QString str;
QTextStream out(stdout);
out << "input data" << endl;
QTextStream in(stdin);
in >> str;
out << "input str = " << str << endl;
QCoreApplication a(argc, argv);
MyThread *pMyThread = new MyThread();
QObject::connect(pMyThread, SIGNAL(finished()), &a, SLOT(quit()));
pMyThread->start();
qDebug() << "test ok" << endl;
return a.exec();
}
4、代碼下載