Note that there are some explanatory texts on larger screens.

plurals
  1. POMake function of root QML component callable for other components
    text
    copied!<p>I want to show a message box, that is implemented in <strong>main.qml</strong> (as a layer above all other components). The function <code>showMessage()</code> makes the QML message box visible and sets the text. So it's possible for code in <strong>main.qml</strong> to show message boxes, but other components (not in <strong>main.qml</strong>) should be able to show message boxes, too.</p> <p>My idea so far is to create a C++ QML component that has a function <code>displayMessage()</code> which calls the <code>showMessage()</code> function of the root context (→ <strong>main.qml</strong>).</p> <p><strong>mail.qml</strong> (root component)</p> <pre><code>import QtQuick 1.0 // [...] Rectangle { id: main function showMessage(text) { // make a message area visible and set text } // [...] // message box implementation } </code></pre> <p><strong>App.qml</strong></p> <pre><code>import QtQuick 1.0 import MessageForwarder 1.0 // implemented in C++ // [...] Rectangle { id: anApp MessageForwarder { id: mf } // ← Possible without this? Component.onCompleted: mf.displayMessage("A message."); // show message // [...] } </code></pre> <p>Is it possible to create something like a static function, that would allow something like <code>MessageForwarder.displayMessage("Foo")</code>, without needing an additional instance of the <code>MessageForwarder</code> component?</p> <p>Or is there any other convenient possibility to use <code>showMessage()</code> in other components?<br> (Maybe something like the <code>Qt</code> global object?)</p> <p>Thanks!</p> <hr> <p>EDIT:</p> <p>I think I found a quite simple solution: As QML is a dynamically scoped language (→ <a href="http://doc.qt.nokia.com/4.7-snapshot/qdeclarativescope.html#component-instance-hierarchy" rel="nofollow">Qt Doc</a>) and all components are nested inside <strong>main.qml</strong>, this simply works:</p> <p><strong>main.qml</strong></p> <pre><code>import QtQuick 1.0 Rectangle { id: main QtObject { id: messageBox // nested for a more modular design function showMessage(text) { // make a message area visible and set text } } // [...] // message box implementation } </code></pre> <p><strong>App.qml</strong></p> <pre><code>import QtQuick 1.0 Rectangle { id: anApp Component.onCompleted: messageBox.showMessage("A message."); // [...] } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload