【问题标题】:What is the proper way to specify a QObject connection as unique?将 QObject 连接指定为唯一的正确方法是什么?
【发布时间】:2013-07-08 18:53:36
【问题描述】:

Qt documentation 为 Qt::ConnectionType 提供以下值:

AutoConnection = 0;
DirectConnection = 1;
QueuedConnection = 2;
BlockingQueuedConnection = 4;
UniqueConnection = 0x80;

很明显,这表明您可以同时拥有BlockingQueuedConnectionUniqueConnection 的连接。但是,仅将这两者与| 运算符组合会导致编译器错误:

connect(foo, SIGNAL(bar()), this, SLOT(bar()),
        BlockingQueuedConnection | UniqueConnection));
error: invalid conversion from 'int' to 'Qt::ConnectionType'

所以参数必须强制转换:

connect(foo, SIGNAL(bar()), this, SLOT(bar()),
        (Qt::ConnectionType) (BlockingQueuedConnection | UniqueConnection)));

在这种情况下,由于某种原因,铸造感觉是错误的。这真的是建立唯一阻塞队列连接的合适方法吗?

【问题讨论】:

    标签: c++ qt enums


    【解决方案1】:

    Qt::ConnectionType 不是标志。您不能对它们使用 | 运算符。一次只能指定一个枚举值。

    【讨论】:

    • 不是标志,但可以使用'|'操作员。甚至documentation encourages to do so:This is a flag that can be combined with any one of the above connection types, using a bitwise OR.
    【解决方案2】:
    Qt::UniqueConnection 0x80 
    

    "这是一个可以与上述任何一种连接类型组合的标志,使用按位或。

    当设置Qt::UniqueConnection 时,如果连接已经存在(即,如果相同的信号已经连接到同一对对象的同一插槽),QObject::connect() 将失败。
    这个标志是在 Qt 4.6 中引入的。”(来自 Qt5.0 文档,http://qt-project.org/doc/qt-5.0/qtcore/qt.html#ConnectionType-enum

    【讨论】:

    • 请注意,此注释已添加到 5.0 版本的 Qt 文档中。在 4.8 文档中,UniqueConnection 是一个常规枚举值,不能与其他选项结合使用。
    【解决方案3】:

    我认为唯一可行的解​​决方案是强制转换,我使用了类似的方法:

    static_cast<Qt::ConnectionType>(Qt::QueuedConnection | Qt::UniqueConnection)
    

    在我的代码中,它按预期工作。

    【讨论】:

      【解决方案4】:

      看起来像 Qt 错误,documentation says 一个东西:This is a flag that can be combined with any one of the above connection types, using a bitwise OR.,练习显示其他东西。至少QObject::connect 代码looks fine

      看起来应该有一些功能请求或错误报告给 Qt。

      我会通过定义一个函数来解决这个问题:

      inline Qt::ConnectionType unique(Qt::ConnectionType typeOfConnection) {
          return static_cast<Qt::ConnectionType>(typeOfConnection | Qt::UniqueConnection);
      }
      

      由于 IMO,这个案例看起来会更好:

      connect(foo, SIGNAL(bar()), this, SLOT(bar()),
              unique(Qt::BlockingQueuedConnection));
      

      【讨论】:

        【解决方案5】:

        根据文档,UniqueConnection 就像AutoConnection;所以我猜你只需要指定Qt::UniqueConnection,就是这样。 Qt 会检测你是否处理不同的线程并做出相应的行为。

        【讨论】:

        • 默认的跨线程连接是 QueuedConnection,而不是 BlockingQueuedConnection。
        猜你喜欢
        • 2014-05-08
        • 2018-11-13
        • 1970-01-01
        • 2011-03-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-10-23
        相关资源
        最近更新 更多