作者:soseast9975 | 来源:互联网 | 2023-02-09 21:25
我有两个Javascript函数fun1
,fun2
在QML中,并希望fun2
在另一个(fun1
)完成之后执行一个(),更准确地说,如何在完成fun2()
后启动.是一个用C++编写的函数,通过继承,如下所示:ImageReader
fun1
ImageReader
QImageProvider
function fun1(){
ImageReader.magic(photo);
}
function fun2(){
myImg.source = "";
myImg.source = "image://ImageReader";
}
fun1();
fun2();
使用场景是我想用C++处理图像,当处理完成后,通过QML Image项显示它.
1> folibis..:
好的,我只想总结那些将寻找相同解决方案的人.
至少有两种方法可以做到这一点:
任务完成后,从C++对象发出信号.
将JS函数传递给C++,这将在任务完成时调用.
测试C++对象声明:
class MyItem : public QObject
{
Q_OBJECT
public:
MyItem(QObject *parent = 0);
Q_INVOKABLE void someAsyncFunc();
Q_INVOKABLE void someAnotherAsyncFunc(QJSValue value);
signals:
void someAsyncFuncFinished();
};
测试C++对象实现:
MyItem::MyItem(QObject *parent) :
QObject(parent) {}
void MyItem::someAsyncFunc()
{
// do some work here
emit someAsyncFuncFinished();
}
void MyItem::someAnotherAsyncFunc(QJSValue value) {
// do some work here
if (value.isCallable()) {
value.call();
}
}
将自定义项目注册为单身人士:
static QObject *my_singleton_provider(QQmlEngine *engine, QJSEngine *scriptEngine)
{
Q_UNUSED(engine)
Q_UNUSED(scriptEngine)
static MyItem *item = nullptr;
if(!item)
item = new MyItem();
return item;
}
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
qmlRegisterSingletonType("Qt.MyTest", 1, 0, "MyItem", my_singleton_provider);
QQmlApplicationEngine engine;
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
return app.exec();
}
所以QML文件来测试它:
1.任务完成时发出的信号
Item {
id: testItem
function func1()
{
console.log("func1 executing...")
MyItem.someAsyncFuncFinished.connect(func2);
MyItem.someAsyncFunc();
}
function func2()
{
console.log("func2 executing...")
}
Component.onCompleted: func1();
}
2.将JS函数传递给C++:
Item {
id: testItem
function func1()
{
console.log("func1 executing...")
MyItem.someAnotherAsyncFunc(func2);
}
function func2()
{
console.log("func2 executing...")
}
Component.onCompleted: func1();
}