Call an AppleScript from Qt

From Qt Wiki
Revision as of 10:04, 24 February 2015 by Maintenance script (talk | contribs)
Jump to navigation Jump to search

English
| Русский
| Italiano
| Español
| Shqip
| Български

If you want to call AppleScript commands from within Qt you can use this code snippet as a starting point.

<br />#include &lt;QApplication&amp;gt;<br />#include &lt;QProcess&amp;gt;<br />#include &lt;QDebug&amp;gt;

int main(int argc, char **argv)<br />{<br /> QApplication a(argc, argv);

QString aScript =<br /> &quot;tell application quot;System Eventsquot;&quot;<br /> &quot; activate\n&amp;quot;<br /> &quot; display dialog quot;Hello worldquot;&quot;<br /> &quot;end tell\n&amp;quot;;

QString osascript = &quot;/usr/bin/osascript&amp;quot;;<br /> QStringList processArguments;<br /> processArguments &lt;&lt; &quot;-l&amp;quot; &lt;&lt; &quot;AppleScript&amp;quot;;

QProcess p;<br /> p.start(osascript, processArguments);<br /> p.write(aScript.toUtf8());<br /> p.closeWriteChannel();<br /> p.waitForReadyRead(1);<br /> QByteArray result = p.readAll();<br /> QString resultAsString(result); // if appropriate<br /> qDebug() &lt;&lt; &quot;the result of the script is&amp;quot; &lt;&lt; resultAsString;

return 0;<br />}<br />

It holds the actual script in variable aScript. Then creates a QProcess for invoking the AppleScript command line tool osascript.

The arguments call osascript with -l AppleScript, so that the it needs not to guess the script language.

The script is then fed to osascript via stdin.

The program waits for some data on the output of the script to come in. We do read the output of the script, hence waitForReadyRead.

If there are bytes available, the program reads them and converts them to a QString (if that is ok for the expected data!). In a real world program on should connect to the various readyReadXXX() signals and connect a slot to it to collect the data.