Tell me what I'm doing wrong. Wrote a simple function that I want to call in qml.

Header:

class BackEnd : public QObject { Q_OBJECT public: explicit BackEnd(QObject *parent = nullptr); void shutDown(); signals: private: }; 

cpp:

 BackEnd::BackEnd(QObject *parent) : QObject(parent) { } void BackEnd::shutDown() { string syscol = "shutdown /s /t 0"; system(syscol.c_str()); } 

In main registered type

qmlRegisterType ("io.backend", 1, 0, "BackEnd");

Inside the qml file, I can call BackEnd, but the shotDown function cannot, what's wrong with the written code?

    2 answers 2

    It is necessary that she got into the moc file:

     class BackEnd : public QObject { Q_OBJECT public: explicit BackEnd(QObject *parent = nullptr); Q_INVOKABLE void shutDown(); ... } 

    ** UPD ** I agree with the companion of ixSci, if the method is not needed as a slot, it is better to write Q_INVOKABLE

    • 2
      You do not need to make a slot that is not. For this there is a Q_INVOKABLE . - ixSci

    In order to see this function, you need to add Q_INVOKABLE before declaring the function in the header:

     class BackEnd : public QObject { Q_OBJECT public: explicit BackEnd(QObject *parent = nullptr); Q_INVOKABLE void shutDown(); signals: private: }; 

    Well, for complete beauty you should change your main:

     int main(int argc, char** argv) { QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling); QGuiApplication app(argc, argv); QQmlApplicationEngine engine; qmlRegisterType<BackEnd>("io.backend", 1, 0, "BackEnd"); BackEnd backEnd; QQmlContext* cntx = engine.rootContext(); cntx->setContextProperty("backEnd", &backEnd); engine.load(QUrl(QStringLiteral("qrc:/main.qml"))); return app.exec(); }