Unsolved how to run even of custom c++ function on close event
-
Hello, let say I have this:
main.cpp:
#include <QQmlApplicationEngine> #include <QGuiApplication> #include <QtQml> #include <QCoreApplication> #include <QtCore> #include "led.h" int main(int argc, char *argv[]) { QGuiApplication app(argc, argv); qmlRegisterType<LED>("LED", 1, 0, "LED"); const QUrl url(QStringLiteral("qrc:/main.qml")); engine.load(url); return app.exec(); }
led.h:
#ifndef LED_H #define LED_H #include <QObject> #include <QSerialPort> class LED : public QObject { Q_OBJECT public: explicit LED(QObject *parent = nullptr); Q_INVOKABLE void setColor(int red, int green, int blue); public slots: private: signals: }; #endif // LED_H
led.cpp:
#include "led.h" #include <QSerialPort> #include <QSerialPortInfo> #include <QtSerialPort/QSerialPort> namespace Stuff { struct ByteArray: public QByteArray { ByteArray(std::initializer_list<unsigned char> lst) : QByteArray(reinterpret_cast<char const *>(lst.begin()), lst.size()) {} }; } QSerialPort m_serial; QString m_port = "COM3"; LED::LED(QObject *parent) : QObject(parent) { } void LED::setColor(int red, int green, int blue) { SOME STUFF WHICH IS NOT IMPORTAN HERE }
and what I need is on close event (alf+f4, hitting the "x" etc) to run function LED::setColor(0,0,0)
where whould be the best place to do this? I have blindly tried to place the LED:::setColor(0,0,0) bellow the return app.exec(); however this is quite nonsence, and also LED::setColor() is not recognized there…can you please advice how to modify the LED::setColor() in order to be recognized? and where is the best place to place this onClose() event script?
Thank you
-
@shokarta
you could try://needs include of QCoreApplication #include <QCoreApplication> LED::LED(QObject *parent) : QObject(parent) { connect(QCoreApplication::instance(), &QCoreApplication::aboutToQuit, this, [=]()->void{setColor(0,0,0)}); }
if it's too late, you probably have to hook into the event system to prevent the close first
-
led.cpp:32:108: error: expected ';' after expression
on that line with:
connect(QCoreApplication::instance(), &QCoreApplication::aboutToQuit, this, =->void{setColor(0,0,0)});
not sure why, to me syntax looks ok :( -
@shokarta sorry my bad I wrote without an editor:
connect(QCoreApplication::instance(), &QCoreApplication::aboutToQuit, this, [=]()->void{setColor(0,0,0);});
it needs a ; after the setColor