1

I am looking for the most simple and straightforward example.

For my part;

.h

public:
KTerminalDisplay(QQuickItem *parent = 0);
~KTerminalDisplay();
Q_INVOKABLE void setFontStyle(QString & s);  

.cpp

void KTerminalDisplay::setFontStyle(QString & s){
m_fontStyle = QString(s);
}

This works fine thus far. No issues. The question is; how do I use this function in a QML file?

1 Answer 1

1

To make the KTerminalDisplay instance accessible from QML, you must register it in your main.cpp. Since you're expecting parent to be a QQuickItem, your question is not so simple. After looking at the terminal app, I can propose the following trick:

QQuickItem *item = view.rootObject();
KTerminalDisplay * display = (KTerminalDisplay *) item;
view.engine()->rootContext()->setContextProperty("kdisplay", display);

Once registered, you can call setFontStyle from QML:

kdisplay.setFontStyle("foo")

Note: See Embedding C++ Objects into QML with Context Properties as you can mark your method as a slot.

Source: http://developer.nokia.com/community/wiki/Calling_Qt_class_methods_from_QML

13
  • What does '...your view" refer to? I am assuming it is the QQuickView object?
    – Anon
    Sep 22, 2014 at 9:18
  • @Akiva: I've updated my answer with a richer context for the main.cpp Sep 22, 2014 at 9:22
  • What is "qtquick2applicationviewer.h" in reference to? The header which contains the kterminaldisplay class?
    – Anon
    Sep 22, 2014 at 9:48
  • @Akiva: Look at my answer here, it's a working piece of code that you can reuse. "qtquick2applicationviewer.h" is a Qt header, not your header containing the kterminaldisplay class. Sep 22, 2014 at 9:53
  • Yah I just saw that. Unfortunately I do not have a .pro file for this, as this project is using cmakelists. Do you know what to do in that case?
    – Anon
    Sep 22, 2014 at 9:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.