方法1
在qtdesigner中设置按钮图标的三个属性,normal off 、normal on和checkable=true。
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5 import uic
from switchBtn import Ui_Dialog
class Test(QDialog, Ui_Dialog):
def __init__(self):
super(Test, self).__init__()
self.setupUi(self)
if __name__ == "__main__":
app = QApplication([])
window = Test()
window.show()
app.exec_()
方法2,通过切换图片
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5 import uic
from switchBtn import Ui_Dialog
class Test(QDialog, Ui_Dialog):
def __init__(self):
super(Test, self).__init__()
self.setupUi(self)
# uic.loadUi("switchBtn.ui", self)
self.pushButton.clicked.connect(self.toggleIcon2)
self.pushButton.setEnabled(True) # false是点不动按钮
self.btn_clicked = False
def toggleIcon2(self):
self.btn_clicked = not self.btn_clicked
if self.btn_clicked:
self.pushButton.setIcon(QIcon('switch_on.png'))
else:
self.pushButton.setIcon(QIcon('switch_off.png'))
print(f"self.btn_clicked: {self.btn_clicked}")
if __name__ == "__main__":
app = QApplication([])
window = Test()
window.show()
app.exec_()
c++qt版本
bool btn_clicked = false;
connect(ui->switchBtn,&QPushButton::clicked,this,[this](){
btn_clicked = !btn_clicked;
if (btn_clicked) {
ui->switchBtn->setIcon(QIcon(":/imgs/switch_on.png"));
} else {
ui->switchBtn->setIcon(QIcon(":/imgs/switch_off.png"));
}
qDebug()<<"btn_clicked:"<<btn_clicked;
});