python - 如何在 PyQt 中使用 Q_ENUMS

标签 python enums properties pyqt qt-designer

我正在创建一个继承自 QLabel 的自定义小部件,我希望我的小部件上有一个属性来表示在向用户呈现时必须如何格式化数据。

为此,我正在尝试使用 Q_ENUMS,但我没有取得太大的成功。我可以获得在设计器中显示的属性,但保存的 UI 文件将枚举显示为 PyDMLabel::STRING 而不是我期望的 DisplayFormat::STRING

这是我的小部件代码:

class PyDMLabel(QLabel, PyDMWidget):
    class DisplayFormat:
        DEFAULT = 0
        STRING = 1
        DECIMAL = 2
        EXPONENTIAL = 3
        HEX = 4
        BINARY = 5

    Q_ENUMS(DisplayFormat)

    """
    A QLabel with support for Channels and more from PyDM

    Parameters
    ----------
    parent : QWidget
        The parent widget for the Label
    init_channel : str, optional
        The channel to be used by the widget.
    """
    def __init__(self, parent=None, init_channel=None):
        QLabel.__init__(self, parent)
        PyDMWidget.__init__(self, init_channel=init_channel)

        self.setTextFormat(Qt.PlainText)
        self.setTextInteractionFlags(Qt.NoTextInteraction)
        self.setText("PyDMLabel")
        self._display_format_type = PyDMLabel.DisplayFormat.DEFAULT

    @pyqtProperty(DisplayFormat)
    def displayFormat(self):
        return self._display_format_type

    @displayFormat.setter
    def displayFormat(self, new_type):
        if self._display_format_type != new_type:
            self._display_format_type = new_type

处理 Q_ENUMS 和 PyQt 的正确方法是什么?

最佳答案

为了让 Qt(设计器)看到枚举,PyQt 必须将它添加到 meta-object自定义类。所以它永远不会被 Qt 称为 DisplayFormat::STRING

在 Qt 中,在类作用域中声明的枚举将它们的常量公开为类的成员。例如,QComboBox类定义了一个 InsertPolicy枚举,常量可以这样引用:QComboBox::InsertAtTop。所以在这方面,PyQt Q_ENUMS 在 Qt Designer 插件中的行为完全符合预期,因为 ui 文件显示 PyDMLabel::STRING

但是,在 Python 代码中获得完全等效的行为需要一些额外的工作。我能想到的最接近的是:

class DisplayFormat:
    DEFAULT = 0
    STRING = 1
    DECIMAL = 2
    EXPONENTIAL = 3
    HEX = 4
    BINARY = 5

class PyDMLabel(QLabel, PyDMWidget, DisplayFormat):
    DisplayFormat = DisplayFormat

    Q_ENUMS(DisplayFormat)

这将仍然导致 Qt Designer 使用 PyDMLabel::STRING(如预期)。但是 Python 代码现在可以通过以下任何方式访问常量:

PyDMLabel.STRING
PyDMLabel.DisplayFormat.STRING
DisplayFormat.STRING

事实上,如果您不介意失去这些选项中的第二个,您可以进一步简化事情:

class DisplayFormat:
    DEFAULT = 0
    ...    

class PyDMLabel(QLabel, PyDMWidget, DisplayFormat):    
    Q_ENUMS(DisplayFormat)

关于python - 如何在 PyQt 中使用 Q_ENUMS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46917671/

相关文章:

c++ - 我如何在 Symbian 上检索 SMS 收件箱消息,最好使用 j2me?

python - 删除标点符号后从文本文件中打印唯一单词列表,并找到最长的单词

c - 枚举无法理解内存和功能

typescript - 使用枚举作为类型允许枚举中不存在的值

Java 验证作为参数传递的枚举值

python - 使用 numpy 获取 3D 空间中所有对象的相对位置

python - 在 Scikit-Learn 特征提取中合并 CountVectorizer

javascript - 如何在 for...in 中获取嵌套对象属性的正确属性?

c# - 将变量绑定(bind)到列表

reference - WiX 属性引用另一个属性