【问题标题】:Python-SIP not converting signal parameters for custom typesPython-SIP 不为自定义类型转换信号参数
【发布时间】:2018-12-12 10:25:58
【问题描述】:

背景

在与 PyQt 相似的风格中,SIP 用于为基于 Qt (Source) 的自定义库生成本机绑定。我正在尝试诊断与为自定义类型提供参数的信号相关的问题,这些信号在传递到各自的插槽时未转换,并且正在寻找要尝试的事情的指针。代码是开源的,我鼓励任何人自己尝试代码,但对于那些想要更简洁/精炼的描述的人,我在这里做了最好的尝试。

问题

让我们从使用导致问题的生成模块的 Python 代码开始 (Interactions Example)。这是MainWindow的构造函数中的标准信号/槽连接代码,完整的源代码可以在mainwindow.py中找到。

class MainWindow(QMainWindow):

    def __init__(self, argv, parent=None):
        # ... snipped other setup code ...

        # connect slot that shows a message in the status bar when a graph is clicked:
        self.customPlot.plottableClick.connect(self.graphClicked)

QCustomPlot 和 plottableClick 信号的定义在 sip/core.sip 中。请注意,plottableClick 信号提供一个 QCPAbstractPlottable* 对象作为第一个参数。

class QCustomPlot : public QWidget
{

    // ... snipped other methods of QCustomPlot type ...

signals:
  void plottableClick(QCPAbstractPlottable *plottable, int dataIndex, QMouseEvent *event);

现在让我们看一下 slot 方法,这也是可能观察到问题的地方。当调用 slot 时,会引发异常,因为 plottable 是一个有效的 PyObject,但它没有类型成员,导致对 interface1D 的调用失败:

def graphClicked(self, plottable, dataIndex):
    dataValue = plottable.interface1D().dataMainValue(dataIndex) # fails because plottable has no member method called "interface1D"

QCPAbstractPlottable 的绑定表明该成员已定义。

class QCPAbstractPlottable : public QCPLayerable /Abstract/
{

  // ... snipped other methods here ...

  virtual QCPPlottableInterface1D *interface1D();

顺便说一句,生成的绑定在调用 QCustomPlot 的成员函数时会正确转换类型,例如返回 QList 的 QCustomPlot.selectedPlottables()。这让我相信问题是特定于信号的。

问题

在我对这个问题进行了几天的努力之后,开始看起来很像 SIP 没有识别库中定义的类型是在传递给它时可以转换的类型所需的信息一个信号。

查看 PyQt5 源代码,我发现库中定义的类型作为信号参数传递的示例,例如 QWidget::mousePressEvent 接受 QMouseEvent*,这与我试图在我的自己的信号。但是,我找不到任何特殊的 SIP 胶水代码来提示代码生成器如何转换类型。

我做错了什么?

【问题讨论】:

标签: python pyqt5 python-sip


【解决方案1】:

事实证明答案很简单,诀窍是使用%ConvertToSubClassCode 指令。在这里,您可以使用任何可用的 rtti 形式(可能是 qobject_cast、dynamic_cast 或任何其他机制)手动编写用于从对象推断类型的逻辑,然后将 sipType 变量设置为正确的值(请参阅链接文档更详尽的解释)。

【讨论】:

  • 如果有人对解决方案的最终应用感兴趣,可以在原始问题中链接的存储库中的提交 917aa5f8bc49d844f6580dc49f43b5303777afda 中找到它。
猜你喜欢
  • 2012-07-01
  • 1970-01-01
  • 1970-01-01
  • 2014-10-13
  • 2022-01-22
  • 2021-03-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多