pushandpop
pushandpop

Reputation: 505

QVariant::QVariant(void*) is private

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.

Upvotes: 5

Views: 7009

Answers (1)

steveire
steveire

Reputation: 11074

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

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

Upvotes: 8

Related Questions