今天用QObject的startTimer()函数启动定时器,结果爆出了下面的错误:
QObject::startTimer: Timers can only be used with threads started with QThread
通过分析发现,Timer启动必须从线程开始启动。下面是我的代码:
TestTypeClass::TestTypeClass()
{
timerId = this->startTimer(1000);
qDebug()<<timerId<<endl;
}
int main(int argc, char *argv[])
{
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
TestTypeClass typeObj;
QGuiApplication app(argc, argv);
qRegisterMetaType<StringList>("StringList");
QQmlApplicationEngine engine;
engine.rootContext()->setContextProperty("TypeObj", &typeObj);
const QUrl url(QStringLiteral("qrc:/main.qml"));
QObject::connect(&engine, &QQmlApplicationEngine::objectCreated,
&app, [url](QObject *obj, const QUrl &objUrl) {
if (!obj && url == objUrl)
QCoreApplication::exit(-1);
}, Qt::QueuedConnection);
engine.load(url);
return app.exec();
}
错误
通过查阅资料发现,QGuiApplication app(argc, argv);代表程序启动的开始,TestTypeClass typeObj;这行代码会创建定时器,应该放在app初始化后面,问题解决。
int main(int argc, char *argv[])
{
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
QGuiApplication app(argc, argv);
TestTypeClass typeObj;
qRegisterMetaType<StringList>("StringList");
QQmlApplicationEngine engine;
engine.rootContext()->setContextProperty("TypeObj", &typeObj);
const QUrl url(QStringLiteral("qrc:/main.qml"));
QObject::connect(&engine, &QQmlApplicationEngine::objectCreated,
&app, [url](QObject *obj, const QUrl &objUrl) {
if (!obj && url == objUrl)
QCoreApplication::exit(-1);
}, Qt::QueuedConnection);
engine.load(url);
return app.exec();
}