How we can connect the signals and slot with different arguments?

前端 未结 4 1119
温柔的废话
温柔的废话 2021-02-02 13:16

In Qt, signals and slots require matching argument types:

QObject::connect: Incompatible sender/receiver arguments QLabel::linkActivated(QString) --> Butt

4条回答
  •  长发绾君心
    2021-02-02 13:59

    As a complementary answer, if you don't want to write an intermediate slot, you can use the lambda expressions (of course with C++11 support) to invoke the method. However, the connector class must know the parameter types used in those particular signals and slots.

    To give an example, assuming that you're trying to connect a signal with a parameter type of QString to a slot with a parameter type of char, you can do it like this;

    class SignalClass{
    signals:
        void testSignal(QString tString);
    };
    
    class SlotClass{
    public slots:
        void testSlot(char tChar);
    };
    
    class ConnectorClass{
    public:
        void connectSignalAndSlot () {
            SignalClass tSigClass;
            SlotClass tSlotClass;
            connect(&tSigClass, &SignalClass::testSignal,
                    [=](QString tString) { this->metaObject()->invokeMethod(tSlotClass,"testSlot", Q_ARG(char, tString.at(0).toLatin1())) }
            );
        }
    }
    

    Kinda ugly stuff, but does the job.

    • No coupled classes
    • No intermediate connector functions

提交回复
热议问题