JSFunction 作为 Qt 槽中的参数?

发布于 2024-10-09 19:41:21 字数 496 浏览 8 评论 0原文

我想编写一个类似于以下 javascript 的 Qt 插槽,

function testFunc( func1,func2,cond )
{
   if ( cond == 1)
   {
            func1();
   }
  else
  {
           func2();
  }
}

我的问题是:

1)。如何接收 Javascript 函数作为参数?
2)。如何再次从 C++ 调用相同的 JS 函数。

这是我的非有效解决方案,

对于 Q.1->将 JSFunction 争论作为 QString 为我提供了完整的函数代码,因此在这种情况下,我需要编写代码来从那里提取函数名称。

对于Q.2->我可以通过 QWebFrame::evaluateJavaScript 调用 JS 函数,但为此我需要构造一个函数名字符串+所有函数参数。

那么对于这个问题有没有更好的解决方案呢?

I want to write a Qt slot similar to following javascript,

function testFunc( func1,func2,cond )
{
   if ( cond == 1)
   {
            func1();
   }
  else
  {
           func2();
  }
}

Questions for me are:

1). how to receive Javascript function as an arguement?
2). how to call same JS function from C++ again.

Here are my non-efficient solutions,

For Q.1-> taking JSFunction arguement as a QString gives me full function code, So in this case I need to write code to extract just function name from there.

For Q.2-> I can call JS function by QWebFrame::evaluateJavaScript, but for this I need to construct a string of function name + all the function arguements.

So is there any better solutions available for this problem?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

指尖微凉心微凉 2024-10-16 19:41:21

不幸的是,目前在 QtWebKit 中不可能以更干净的方式做到这一点。我们付出了一些努力来添加完整的 JavaScript <-> C++ 绑定到 QtWebKit,位于 QtScript 之上,但我不确定这方面的进展是什么。

这意味着您只剩下您提到的两个解决方案(但我强烈建议避免第一个解决方案,因为它很糟糕并且不适用于匿名函数对象)。

另一个解决方案是创建两个信号:conditionSatisfied() 和conditionFailed() 并将它们分别连接到func1、func2:

function func1() { ... }
function func2() { ... }

object.conditionSatisfied.connect(func1);
object.conditionFailed.connect(func2);

然后,在C++ 方面:

void X::testFunc(const QVariant& cond)
{
    if (cond.toInt() == 1)
        emit conditionSatisfied();
    else
        emit conditionFailed();
}

这不是一个好的设计,但你不能做得更好。

Unfortunately, it's impossible to do this in a cleaner way in QtWebKit, at this point. There's been some effort to add full JavaScript <-> C++ bindings to QtWebKit, on top of QtScript, but I'm not sure what the progress on that is.

That means you're left with the two solutions you mentioned (but I strongly recommend avoiding the first one as it's hackish and doesn't work with anonymous function objects).

Another solution would be to create two signals: conditionSatisfied() and conditionFailed() and connect those to func1, func2, respectively:

function func1() { ... }
function func2() { ... }

object.conditionSatisfied.connect(func1);
object.conditionFailed.connect(func2);

Then, on the C++ side:

void X::testFunc(const QVariant& cond)
{
    if (cond.toInt() == 1)
        emit conditionSatisfied();
    else
        emit conditionFailed();
}

That's not a good design but you can't do better.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文