我在我的项目中使用 C++ 和 Qt4.5.2(目标系统的要求)。需要一个提供附加参数/参数的工作线程,所以我做了以下操作(简而言之,删除了错误处理/输出):
bool _bRetVal = false;
COpgThread* _pParseThread = new COpgThread(); // COpgThread is subclassed from QThread to access the protected msleep-function
COpgWorker* _pParseWorker = new COpgWorker(); // COpgWorker is subclassed from QObject to provide: slots (process) and signals (finished, progress, error) for a COpgThread-instance
QSignalMapper* _pParseMapper = new QSignalMapper();
COpgParam _pParseParam = new COpgParam(m_sParseFile, m_sRegExpFile); // COpgParam is subclassed from QObject to handle user data for mapping
_pParseWorker->moveToThread(_pParseThread);
//#1 hookup error-signal from worker to errorParsing-function in this object
_bRetVal = QObject::connect(_pParseWorker, SIGNAL(error(int const)), this, SLOT(errorParsing(int const)));
//#2..3 hookup thread's started-signal to process-slot in the worker (via signal mapper for parameters/arguments)
_bRetVal = QObject::connect(_pParseThread, SIGNAL(started()), _pParseMapper, SLOT(map()));
_pParseMapper->setMapping(_pParseThread, _pParseParam);
_bRetVal = QObject::connect(_pParseMapper, SIGNAL(mapped(QObject*)), _pParseWorker, SLOT(process(QObject*)));
//#4 hookup progress-signal from worker to progessParsing-function in this object
_bRetVal = QObject::connect(_pParseWorker, SIGNAL(progress(int const)), this, SLOT(progressParsing(int const)));
//#5 hookup finished-signal from worker to completedParsing-function in this object
_bRetVal = QObject::connect(_pParseWorker, SIGNAL(finished(int const)), this, SLOT(completedParsing(int const)));
//#6 when worker emits finished-signal, signal thread to quit (shutdown)
_bRetVal = QObject::connect(_pParseWorker, SIGNAL(finished(int const)), _pParseThread, SLOT(quit()));
//#7 when worker emits finished-signal, mark worker to be deleted
_bRetVal = QObject::connect(_pParseWorker, SIGNAL(finished(int const)), _pParseWorker, SLOT(deleteLater()));
//++++ this connect fails at runtime ++++
//#8 when thread emits finished-signal, mark mapper to be deleted
_bRetVal = QObject::connect(_pParseThread, SIGNAL(finished(int const)), _pParseMapper, SLOT(deleteLater()));
//+++++++++++++++++++++++++++++++++++++++
//#9 when thread emits finished-signal, mark thread to be deleted
_bRetVal = QObject::connect(_pParseThread, SIGNAL(finished(int const)), _pParseThread, SLOT(deleteLater()));
_pParseThread->start();
整个代码编译没有任何错误,但第 8 次连接在运行时失败。我想,当我创建 QSignalMapper 的实例时......它必须在某个时候被删除。也许这是浪费的代码。我对Qt不是很熟悉。
有什么建议么?
提前致谢。