本文介绍了Qt转发信号/插槽连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们说 SomeClass 有成员 Object1 Object2 并且 Object1 Object2 之间有类似的连接:

Let's say SomeClass has members Object1 and Object2 and there is a connection between Object1 and Object2 like:

connect(Object1, signal1, Object2, slot1)

在将 Object3 添加到 SomeClass Object2 之后,移动为 Object3 的成员,但仍然存在对 Object1 和 Object2 。

After some refactoring Object3 was added to SomeClass and Object2 was moved to be a member of Object3, but still exist the need for the connection between Object1 and Object2.

Object1 Object2 之间的通讯必须立即通过 Object3 。这意味着 Object3 需要修改,添加一对signal / slot只是为了实现 Object1 code> Object2 。

The communication between Object1 and Object2 will have to go through Object3 now. This means Object3 needs to be modified, adding a pair of signal/slot just to implement that communication between Object1 and Object2.

这意味着 Object3 和.cpp将被修改,添加许多行代码来做一个以前在一行中完成的事情。

This means both Object3's .h and .cpp will be modified, adding many lines of code to do a thing previously done in just one line.

我的懒惰的一面是告诉这里有一些奇怪的东西故事。

My lazy side is telling that there is something strange in this story. Is there some way to make that connection more straight forward?

推荐答案

你正在封装 Object2 Object3 内。从 Object3 用户的角度来看,没有什么改变:仍然只有一行代码来设置连接。 Object3 需要一个额外的槽,转发到它现在封装的 Object2 实例。这是一个额外行。就是这样。

You're encapsulating Object2 within Object3. From the point of view of the user of Object3, nothing is changing: there's still only one line of code to set up the connection. Object3 needs an extra slot that forwards to the Object2 instance it now encapsulates. That's one extra line here. And that's it.

struct Object1 : QObject {
  Q_SIGNAL void signal1();
  Q_OBJECT
};
struct Object2 : QObject {
  Q_SLOT void slot1() {}
  Q_OBJECT
};
class Object3 : QObject {
  Q_OBJECT
  Object2 m_object2;
public:
  // one line to expose object2's slot
  Q_SLOT void slot1() { m_object2.slot1(); }
};

class SomeClass {
  Object1 m_object1;
  Object3 m_object2;
public:
  SomeClass() {
    // still one line
    connect(&m_object1, &Object1::signal1, &m_object3, &Object3::slot1);
  }
};

这篇关于Qt转发信号/插槽连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-01 09:19