I have a class that has a Q_PROPERTY
called rotationVal
, and I'm exposing that class using qmlRegisterType
in main.cpp
.
I'm receiving an int value from Java side which I'm using to set the value of rotationVal
(eg: setRotationVal(rotationVal)
).
This works perfectly fine when I access rotationVal
in QML, but I'm told to use the setRotationVal()
from Qt's "UI thread". Can anyone explain?
imageorientation.h
#ifndef IMAGEORIENTATION_H
#define IMAGEORIENTATION_H
#include <QObject>
class ImageOrientation:public QObject
{
Q_OBJECT
Q_PROPERTY(int rotation READ rotation WRITE setRotation NOTIFY rotationChanged)
public:
explicit ImageOrientation(QObject* parent = nullptr);
int rotation() const;
void setRotation(int newRotation);
signals:
void rotationChanged();
private:
int m_rotation;
};
#endif // IMAGEORIENTATION_H
imageorientation.cpp
#include "imageorientation.h"
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QJniObject>
#include <QDebug>
#include <QObject>
ImageOrientation::ImageOrientation(QObject *parent) : QObject{parent}
{
QJniObject javaClass = QNativeInterface::QAndroidApplication::context();
javaClass.callMethod<void>("setPointer","(J)V",(long long)(ImageOrientation*)this);
setRotation(0);
}
extern "C" {
JNIEXPORT void JNICALL Java_com_example_myapplication_MainActivity_setNativeRotation
(JNIEnv *, jobject, jint rotation, jlong ptr){
ImageOrientation* orientation = reinterpret_cast<ImageOrientation*>(ptr);
if(rotation == 90)
rotation = 270;
else if(rotation == 270)
rotation = 90;
orientation->setRotation(rotation);
qDebug() << rotation;
}
}
int ImageOrientation::rotation() const
{
return m_rotation;
}
void ImageOrientation::setRotation(int newRotation)
{
if (m_rotation == newRotation)
return;
m_rotation = newRotation;
emit rotationChanged();
}
Main.qml
import QtQuick
import QtQuick.Window
import ImageOrientationpackage
Window {
width: 640
height: 480
visible: true
title: qsTr("Image Rotation")
ImageOrientation {
id: imgOrientation
}
Rectangle {
width: parent.width
color: "grey"
height: 40
Text {
text: "Image Rotation"
font.pointSize: 32
color: "white"
}
}
Image {
id: image
source: "qrc:/images/exampleimg.png"
width: 200
height: 200
anchors.centerIn: parent
rotation: imgOrientation.rotation
}
}