Reputation:
So let's suppose I've got a regular Qt class MyQtClass
and a class MyClass
with ONLY static members. If I want to access the ui of MyQtClass
I have to use Signals and Slots. So I create a static Signal (static so I can just invoke it like MyClass::mySignal();
) and a slot in the Qt class. How can I connect the static signal from MyClass with the slot from the Qt class, without having an object of MyClass
, since it has only got static members?
I know that classes with only static members isn't considered as a good design in c++ but I'm too far into the project by now and I want to know if there's a way to do it with only static members.
Thanks in Advance!
Code:
MyQtClass.h:
#include "ui_MyQtClass.h"
class MyQtClass : public QMainWindow
{
Q_OBJECT
public:
MyQtClass(QWidget *parent = Q_NULLPTR);
Q_SLOT void mySlot();
private:
Ui::MyQtClassClass ui;
};
MyClass.h:
#pragma once
#include <QtWidgets/QMainWindow>
class MyClass : public QObject
{
public:
static void myFunction1();
static void myFunction2();
/*--- More Stuff ---*/
Q_SIGNAL static void mySignal();
};
Upvotes: 2
Views: 2328
Reputation: 243993
As indicated in this thread it is not possible to emit static signals since it is always associated with a QObject
, as an alternative they create a singleton that would be equivalent to what you want.
#include <QtCore>
class Receiver: public QObject
{
Q_OBJECT
public:
using QObject::QObject;
Q_SLOT void mySlot(){
qDebug()<< __PRETTY_FUNCTION__;
QCoreApplication::quit();
}
};
class Sender: public QObject
{
Q_OBJECT
using QObject::QObject;
public:
static Sender& instance(){
static Sender m_instance;
return m_instance;
}
static void myFunction1(){
emit instance().mySignal();
}
Q_SIGNAL void mySignal();
};
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
Receiver r;
QObject::connect(&Sender::instance(), &Sender::mySignal, &r, &Receiver::mySlot);
QTimer::singleShot(1000, &Sender::myFunction1);
return a.exec();
}
#include "main.moc"
Upvotes: 2