How to create toggle switch button in qt designer?

后端 未结 2 1787
执笔经年
执笔经年 2021-01-06 19:07

I am trying to create toggle button in qt designer. I refer on internet also but i couldn\'t find how to do that. Can anyone know how to do toggle switch button. I have atta

2条回答
  •  灰色年华
    2021-01-06 19:46

    A possible solution is to use a stylesheet with a QCheckBox. Just edit the stylesheet for the check box with the following code:

        QCheckBox::indicator:unchecked {
            image: url(switch_off.png);
        }
        QCheckBox::indicator:checked {
            image: url(switch_on.png);
        }
    

    Minimal running example:

    from PyQt5 import QtWidgets
    import sys
    
    app = QtWidgets.QApplication(sys.argv)
    switch = QtWidgets.QCheckBox()
    switch.setStyleSheet('''
        QCheckBox::indicator:unchecked {
            image: url(switch_off.png);
        }
        QCheckBox::indicator:checked {
            image: url(switch_on.png);
        }
    ''')
    switch.show()
    sys.exit(app.exec_())
    

    Unfortunately, this doesn't always work well if you need some resizing and want the checkbox to adjust its appearance.

    The only alternative is to subclass a QPushButton/QAbstractButton (with the checkable() property set to True) and implement the paintEvent on your own, as already suggested by the answer from eyllanesc.

提交回复
热议问题