老师原课件下载地址:
有积分的朋友,支持下我,打赏也OK。
不下载也可以,我每节课会吧代码贴出来
视频链接
课程重点
代码位置
完整代码
'''
复选框控件(QCheckBox)
3种状态
未选中:0
半选中:1
选中:2
'''
import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import Qt
class QCheckBoxDemo(QWidget):
def __init__(self):
super(QCheckBoxDemo,self).__init__()
self.initUI()
def initUI(self):
self.setWindowTitle('复选框控件演示')
layout = QHBoxLayout()
self.checkBox1 = QCheckBox('复选框控件1')
self.checkBox1.setChecked(True)
self.checkBox1.stateChanged.connect(lambda:self.checkboxState(self.checkBox1))
layout.addWidget(self.checkBox1)
self.checkBox2 = QCheckBox('复选框控件2')
self.checkBox2.stateChanged.connect(lambda:self.checkboxState(self.checkBox2))
layout.addWidget(self.checkBox2)
self.checkBox3 = QCheckBox('半选中')
self.checkBox3.stateChanged.connect(lambda:self.checkboxState(self.checkBox3))
self.checkBox3.setTristate(True)
self.checkBox3.setCheckState(Qt.PartiallyChecked)
layout.addWidget(self.checkBox3)
self.setLayout(layout)
def checkboxState(self,cb):
check1Status = self.checkBox1.text() + ', isChecked=' + str(self.checkBox1.isChecked()) + ',checkState=' + str(self.checkBox1.checkState()) + '\n'
check2Status = self.checkBox2.text() + ', isChecked=' + str(self.checkBox2.isChecked()) + ',checkState=' + str(self.checkBox2.checkState()) + '\n'
check3Status = self.checkBox3.text() + ', isChecked=' + str(self.checkBox3.isChecked()) + ',checkState=' + str(self.checkBox3.checkState()) + '\n'
print(check1Status + check2Status + check3Status)
if __name__ == '__main__':
app = QApplication(sys.argv)
main = QCheckBoxDemo()
main.show()
sys.exit(app.exec_())
遇到的问题
改写效果展示
改写注意点
self.checkBox3.setCheckState(Qt.PartiallyChecked)
这里连接的时候必须增加lambda,因为传参了就不是一个函数调用了,所以需要用不带参的lambda封装成无名函数。
self.ui.checkBox1.stateChanged.connect(lambda :self.checkboxState(self.ui.checkBox1))
老师这里定义的传参貌似没有调用,我修改了下,可以起作用了:
改写代码(QTdesigner模式)
# -*- coding:utf-8 -*-
'''
@Author: knocky
@Blog: https://blog.csdn.net/zzx188891020
@E-mail: 188891020@qq.com
@File: class_X.py
@CreateTime: 2020/5/11 23:36
'''
import sys
from PyQt5.QtWidgets import QApplication
from PyQt5 import uic
class my_form():
def __init__(self):
super().__init__()
self.ui = uic.loadUi("../ui_package/class39.ui")
self.ui.checkBox1.stateChanged.connect(lambda :self.checkboxState(self.ui.checkBox1))
self.ui.checkBox2.stateChanged.connect(lambda :self.checkboxState(self.ui.checkBox2))
self.ui.checkBox3.stateChanged.connect(lambda :self.checkboxState(self.ui.checkBox3))
def checkboxState(self,cb):
list_status= cb.text() + ', isChecked=' + str(cb.isChecked()) + ',checkState=' + str(cb.checkState())
print(list_status)
if __name__ == '__main__':
app = QApplication(sys.argv)
main = my_form()
main.ui.show()
sys.exit(app.exec_())