我正试图让一个线程在mainwindow.cpp
中调用函数testing()
,每次X秒。
我已经实现了一个名为AutoSaveThread
的类。
头文件如下所示:
#ifndef AUTOSAVETHREAD_H
#define AUTOSAVETHREAD_H
#include <QtCore>
#include <unistd.h>
class AutoSaveThread : public QThread
{
public:
AutoSaveThread(QObject*);
void run();
signals:
void callTest();
};
#endif // AUTOSAVETHREAD_H
.cpp方法看起来像文件这样:
#include "autosavethread.h"
AutoSaveThread::AutoSaveThread(QObject *parent){
connect(this, SIGNAL(callTest()), parent, SLOT(testing()));
}
void AutoSaveThread::run()
{
while(true){
sleep(3);
emit callTest();
// call autosave in mainwindow.cpp
}
}
main.cpp是我创建线程的地方,如下所示:
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
AutoSaveThread myThread(&w);
myThread.start();
w.show();
return a.exec();
}
测试功能为:
void MainWindow::testing()
{
qDebug()<<"nice";
}
当我尝试运行此代码时,我得到以下输出:
Undefined symbols for architecture x86_64:
"AutoSaveThread::callTest()", referenced from:
AutoSaveThread::run() in autosavethread.o
ld: symbol(s) not found for architecture x86_64
如有任何帮助,我们将不胜感激!
编辑:
在做出更改后@Jens建议我得到以下错误:
"AutoSaveThread::callTest()", referenced from:
AutoSaveThread::run() in autosavethread.o
"vtable for AutoSaveThread", referenced from:
AutoSaveThread::AutoSaveThread(QObject*) in autosavethread.o
NOTE: a missing vtable usually means the first non-inline virtual member function has no definition.
ld: symbol(s) not found for architecture x86_64
如果您想每X秒在Qt中运行一个处理程序,那么您根本不需要创建线程。只需实例化一个QTimer
,用QTimer::setInterval()
设置所需的间隔,并将QTimer::timeout
信号连接到要运行的插槽/处理程序。
关于一个工作示例,请查看QTimer
文档页面上的详细信息部分。
首先:您没有运行程序,正在尝试编译它,但您得到的是一个构建错误:您缺少callTest((的实现。
为了使用信号和槽,autosavethread.h的头必须使用moc编译器进行编译。这将生成丢失的方法。
moc生成的文件必须进行编译,并与其他源链接。
要做到这一点,你的课程必须配备关键词Q_OBJECT:
class AutoSaveThread : public QThread
{
Q_OBJECT
public:
建议:使用Qt Creator并从一个简单的示例开始。然后继续使用线程。线程化会让事情变得更加模糊——尤其是如果你在启动主程序之前启动线程,你可能会遇到各种各样的问题。