Create a method for a custom type for QML created by QT c++
Solved
QML and Qt Quick
-
Hi everybody,
I'm trying to add a new custom type to the QML.
Everything works fine except I don't know how to add its own functions to the new type created:My .h file is:
#ifndef SERIALCOMMUNICATION_H #define SERIALCOMMUNICATION_H #include <QObject> #include <QSerialPort> #include <QByteArray> #include <QtQuick> class SerialCommunicationtoQML: public QObject { Q_OBJECT Q_PROPERTY(QString name READ name WRITE setName NOTIFY nameChanged) Q_PROPERTY(int numAvailablePorts READ numAvailablePorts WRITE setnumAvailablePorts NOTIFY numAvailablePortsChanged) public: SerialCommunicationtoQML(QQuickItem *parent = 0); QString name() const; void setName(const QString &name); int numAvailablePorts() const; void setnumAvailablePorts(const int &numAvailablePorts); void getPortInfo(); signals: void nameChanged(); void numAvailablePortsChanged(); private: QString m_name; int m_numAvailablePorts; }; #endif // SERIALCOMMUNICATION_H
Then my .cpp file is:
#include "serialcommunication.h" SerialCommunicationtoQML::SerialCommunicationtoQML(QQuickItem *parent) : QObject(parent) { //Aquí podem inicialitzar les variables amb el seu valor per defecte m_numAvailablePorts = 0; } QString SerialCommunicationtoQML::name() const { return m_name; } void SerialCommunicationtoQML::setName(const QString &name) { if (name != m_name) { m_name = name; emit nameChanged(); } } int SerialCommunicationtoQML::numAvailablePorts() const { return m_numAvailablePorts; } void SerialCommunicationtoQML::setnumAvailablePorts(const int &numAvailablePorts) { if (numAvailablePorts != m_numAvailablePorts) { m_numAvailablePorts = numAvailablePorts; emit numAvailablePortsChanged(); } } void SerialCommunicationtoQML::getPortInfo() { }
And finally my .qml file (for testing ) is:
import QtQuick 2.4 import QtQuick.Window 2.2 import SerialCommunication.toQML 1.0 Window { visible: true height: 700 width: 700 Rectangle { color: "lightblue" anchors.centerIn: parent width: parent.width/2 height: parent.width/2 Text { anchors.centerIn: parent text:"El nom és " + serial.name + "\nNúm de ports disponibles: " + serial.numAvailablePorts } SerialCommunication { id: serial name: "INITIAL NAME" } } MouseArea{ anchors.fill: parent onClicked: { console.log("CLICKED ") serial.getPortInfo() } } }
So when I press the mouse area, I expect to go to the getPortInfo function but:
qrc:/main.qml:33: TypeError: Property 'getPortInfo' of object SerialCommunicationtoQML(0x16c5da0) is not a function
Thank you!
-
Hi! The functions that shall be callable from QtQuick must be declared as either slot or invokable, e.g.:
public: Q_INVOKABLE void getPortInfo();
-
Thank you very much @Wieland ,
Now it's working!