开发者

JSFunction as parameter in Qt slot?

开发者 https://www.devze.com 2023-02-01 09:16 出处:网络
I want to write a Qt slot similar to following javascript, function testFunc( func1,func2,cond ) { if ( cond == 1)

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 argueme开发者_开发技巧nt 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?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消