Change mousecursor from QML with setContextProperty and Qt::CursorShape
This is not a request for help. Just a post showing people how to do this.
My case was as follows. I needed to change my cursor shape to Qt::SizeVerCursor for some resizing QML component that i'm making. But i didn't want to make my own QML component just for that so i made a utils class which is assigned to QML by using setContextProperty. In that class i had a function with this:
@Q_INVOKABLE void setCursor(Qt::CursorShape shape);@
That however doesn't work when calling from QML. It does when you make a own custom component, but apparently it doesn't when you use setContextProperty. This is very annoying because all the Qt::CursorShape values are available in QML right now under Qt.<enum_name> so Qt.SizeVerCursor would work for me in passing the value like so:
Note: <property> is the value you set when using setContextProperty.
Sadly, the function argument to allow the type: Qt::CursorShape isn't registered and doesn't want to be registered with qmlRegisterType since it's not an object, just an enum...
So i had the issue of not being able to pass Qt::CursorShape as a function argument when i'm using setContextProperty.
Now i could go for this solution: http://qt-project.org/forums/viewthread/1886 (passing a string to the function) which would make the call something like this:
That's obviously not what i wanted to do. Now here comes a neat trick. Enums are just int numbers so you can pass them in a function that accepts an int argument. The function look like this:
@Q_INVOKABLE void setCursor(int shape);@
Now in QML you can simply do:
In the C++ side you can just check like this:
@void ClassName::setCursor(int shape)
if(shape == Qt::SizeVerCursor)
// ... do something with it
This works and allows you to use the full enum of http://qt-project.org/doc/qt-4.8/qt.html#CursorShape-enum without the need to add some custom string parsing/checking.
What i would've liked more is just the ability to register a function argument type. Apparently that's only possible when sending full blown objects to QML, not with setContextProperty ...
This probably helps a few people out there :)
Note: in QML 2 this is a lot easier if you need to change the cursor shape on some MouseArea. There is just a property for it in QML 2: http://doc-snapshot.qt-project.org/5.0/qml-qtquick2-mousearea.html#cursorShape-prop