3
votes

I'm trying to expose C++ object to QML using setProperty();. Here's a prototype of my code:

MyClass.h

class MyClass::public QObject
{
    Q_OBJECT

public:
    explicit MyClass(QObject *parent = 0);
    ~MyClass();

private:
    QScreen *screen;
    QPixmap myPixmap;
};

MyClass.cpp

MyClass::MyClass (QObject *parent) : QObject(parent)
{
    screen = QGuiApplication::primaryScreen();
}

MyClass::~MyClass()
{

}

void MyClass::captureIt()
{
    myPixmap = screen->grabWindow(0);
    myPixmap.save("/home/john/Pictures/screen.png");
}

usage in main.cpp

QQmlApplicationEngine engine;
MyClass mc;

engine.rootContext()->setProperty("myclass", &mc);
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));

usage in main.qml

onClicked: mc.captureIt()

When I try to compile something wrong happens, because there's strange error about QVariant (the one mentioned in the title of the question).

Do you have any minds how can I solve that?

Update It's not a duplicate of what ringo has posted in the comments below. The problem is not that I can't convert my class to QVariant. I can. But the problem is that setProperty() doesn't let me do it. I have to put my exactly plain object there.

1
@ringø, can you explain how is this the duplicate to what I've asked? - pushandpop
Please read the question up to the bottom, same problem. Then read the answer that may help you... - Déjà vu
@ringø, I've updated my question - pushandpop
It's setContextProperty that you should use. That's it. - BaCaRoZzo

1 Answers

6
votes

You need to use QVariant::fromValue to create a QVariant from a pointer:

engine.rootContext()->setProperty("myclass", QVariant::fromValue(&mc));