我正在为我的应用程序设置资源管理器类。要管理所有资源状态,如果没有成功捕获资源,我需要从构造函数中发出一个Signal。
实际上我想从QObject Derived Class的构造函数发出信号,该构造函数通过qmlRegisterType注册到qml。
这是我在运行MySql和Qt 5.12.2的Linux上测试过的代码。但发射信号不起作用。
myresoureces.cpp ----我的管理资源的类
MyResource::MyResource(QObject *parent) : QObject(parent)
{
if(!openResource()) {
// qDebug() << "Check Permission of FileSystem For Example.";
emit openResourceFailed("Check Permission of FileSystem For Example.");
}
}
bool MyResource::openResource()
{
// on situation opening resource failed
return false;
}
main.qml ----在qml中使用它
// ...
import My.Company.Core 1.0
// ...
MyResource {
onOpenResourceFailed: {
msgDialog.title = "Open Resource Failed!"
msgDialog.text = error
msgDialog.open()
}
}
MessageDialog {
id: msgDialog
}
// ...
main.cpp ----我在哪里注册类
qmlRegisterType<MyResource>("My.Company.Core", 1, 0, "MyResource");
我希望打开消息对话框,但什么都没发生。
信号将调用信号发射时连接的方法,在构造函数的情况下没有连接到任何插槽,因此数据将丢失,可能的解决方案是使用QTimer::singleShot(0, ...)
后发出一会儿创作:
MyResource::MyResource(QObject *parent=nullptr) : QObject(parent){
if(!openResource()) {
QTimer::singleShot(0, this, [this](){
emit openResourceFailed("Check Permission of FileSystem For Example.");
});
}
}
另一种替代解决方案是使用QQmlParserStatus作为接口并以componentComplete()
方法发出信号:
*。H
#ifndef MYRESOURCE_H
#define MYRESOURCE_H
#include <QObject>
#include <QQmlParserStatus>
class MyResource: public QObject, public QQmlParserStatus
{
Q_OBJECT
Q_INTERFACES(QQmlParserStatus)
public:
MyResource(QObject *parent=nullptr);
void classBegin();
void componentComplete();
signals:
void openResourceFailed(const QString & error);
private:
bool openResource();
};
#endif // MYRESOURCE_H
* CPP
#include "myresource.h"
MyResource::MyResource(QObject *parent) : QObject(parent){}
void MyResource::classBegin(){}
void MyResource::componentComplete(){
if(!openResource()) {
emit openResourceFailed("Check Permission of FileSystem For Example.");
}
}
bool MyResource::openResource(){
// on situation opening resource failed
return false;
}