Checkable [QGroupBox] reverse False/True to Block/Unblock the content items

问题描述

正常操作:

  • 如果选中>所有字段都处于活动状态!
  • 如果未选中 > 所有字段都被阻止!

有什么办法可以扭转这种局面? 当用户选中时,我想阻止 qgroupbox 内的所有小部件。

解决方法

一个可能的解决方案是只改变绘画,即如果QGroupBox的checked属性的状态为true则不绘制复选框,否则如果绘制复选框。

import sys
from PyQt5 import QtWidgets


class GroupBox(QtWidgets.QGroupBox):
    def paintEvent(self,event):
        painter = QtWidgets.QStylePainter(self)
        option = QtWidgets.QStyleOptionGroupBox()
        self.initStyleOption(option)
        if self.isCheckable():
            option.state &= ~QtWidgets.QStyle.State_Off & ~QtWidgets.QStyle.State_On
            option.state |= (
                QtWidgets.QStyle.State_Off
                if self.isChecked()
                else QtWidgets.QStyle.State_On
            )
        painter.drawComplexControl(QtWidgets.QStyle.CC_GroupBox,option)


def main():
    app = QtWidgets.QApplication(sys.argv)
    groupbox = GroupBox(checkable=True)
    groupbox.resize(640,480)
    groupbox.show()

    vbox = QtWidgets.QVBoxLayout()

    for i in range(10):
        le = QtWidgets.QLineEdit()
        vbox.addWidget(le)

    groupbox.setLayout(vbox)

    sys.exit(app.exec_())


if __name__ == "__main__":
    pass
    main()