【问题标题】:Has-a relationships and signals in QtQt 中的 Has-a 关系和信号
【发布时间】:2015-01-01 16:10:13
【问题描述】:

我是 Qt 开发的新手,我们的设计在几个地方使用了 has-a 关系。在某些情况下,容器应该公开内部对象的信号,然后我目前为每个此类信号编写了一个私有插槽,实际上我在其中再次重新发出信号。 Qt 中是否有一些捷径可以帮助在容器上暴露内部对象的信号?

【问题讨论】:

    标签: c++ qt


    【解决方案1】:

    您不必为重新发送信号创建插槽,您可以将一个信号与另一个信号连接起来。这样,您将避免插槽定义。

    所以在你的容器中你会有这样的东西:

    connect(object, SIGNAL(signal1()), this, SIGNAL(signal1()));
    

    当然,您必须重新定义容器上的信号。

    更多详情请查看signal slot documentation

    【讨论】:

      【解决方案2】:

      来自documentation

      您可以将任意数量的信号连接到单个插槽,并且可以将信号连接到任意数量的插槽。甚至可以将一个信号直接连接到另一个信号。 (这将在第一个信号发出时立即发出第二个信号。)

      以下是合法的:

      connect(sender, SIGNAL(originalSignal()), SIGNAL(newSignal()));
      

      【讨论】:

        【解决方案3】:

        信号的重新发射也允许重新发射多个信号。

        测试类.h:

        #include <QObject>
        #include <QDebug>
        
        class TestClass : public QObject
        {
        Q_OBJECT
        public:
            explicit TestClass(QObject *parent = 0)
            {
                connect(this, SIGNAL(signal1()), this, SIGNAL(signal2()));
                connect(this, SIGNAL(signal1()), this, SIGNAL(signal2()));
                connect(this, SIGNAL(signal2()), this, SLOT(slot()));
            }
            void emitSignal1()
            {
                emit signal1();
            }
        
        signals:
            void signal1();
            void signal2();
        
        public slots:
            void slot()
            {
                qDebug() << "SLOT HAS BEEN CALLED";
            }
        };
        

        main.cpp:

        #include <QCoreApplication>
        #include "testclass.h"
        
        int main(int argc, char *argv[])
        {
            QCoreApplication a(argc, argv);
        
            TestClass instance;
        
            instance.emitSignal1();
        
            return a.exec();
        }
        

        结果是这种情况下slot被调用了两次。

        【讨论】:

          【解决方案4】:

          如果它是你类的内部结构,你为什么不让它成为朋友类。然后你可以在你的内部结构里面直接调用emit parentObj-&gt;signal()

          【讨论】:

            猜你喜欢
            • 2021-11-02
            • 1970-01-01
            • 2011-02-19
            • 2016-07-09
            • 1970-01-01
            • 1970-01-01
            • 2016-03-23
            • 1970-01-01
            相关资源
            最近更新 更多