我使用的是python3和PyQt5。
下面的示例有三个QPushButtons和一个设置为true的QCheckBox。我可以直接点击复选框,它会在这三个状态之间循环。
问题:如果我试图从相邻的按钮设置状态值,它只会让我选中或不选中。这让人抓狂。
#!/usr/bin/env python3
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
import sys
class Example(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
hbox = QHBoxLayout(self)
qb1=QPushButton("Uncheck it")
qb2=QPushButton("Partial Check it")
qb3=QPushButton("Check it reals")
qb1.clicked.connect(self.uncheck_it)
qb2.clicked.connect(self.partial_check_it)
qb3.clicked.connect(self.check_it)
self.qch=QCheckBox("Chonk")
self.qch.stateChanged.connect(self.chonker)
self.qch.setTristate(True)
hbox.addWidget(self.qch)
hbox.addWidget(qb1)
hbox.addWidget(qb2)
hbox.addWidget(qb3)
self.setLayout(hbox)
self.move(300, 200)
self.setWindowTitle('Choooo')
self.show()
def chonker(self):
print("chonker", self.sender().text(),self.sender().isChecked())
def uncheck_it(self):
self.qch.setChecked(Qt.Unchecked)
print ("Uncheck it")
def partial_check_it(self):
self.qch.setChecked(Qt.PartiallyChecked)
print ("Partial check it")
def check_it(self):
self.qch.setChecked(Qt.Checked)
print ("Check it")
def main():
app = QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
setChecked()
方法只更改为两种状态:已检查或未检查。如果您想更改为所有3种状态,则必须使用setCheckState()
方法:
def uncheck_it(self):
self.qch.setCheckState(Qt.Unchecked)
print("Uncheck it")
def partial_check_it(self):
self.qch.setCheckState(Qt.PartiallyChecked)
print("Partial check it")
def check_it(self):
self.qch.setCheckState(Qt.Checked)
print("Check it")
感谢用户eyllanesc!
在下面的代码中,使用了适用于三态复选框的备用函数。
将函数setChecked替换为函数setCheckState。被替换的函数是用实际返回三态值的函数checkState进行检查的。
这个有效!
#!/usr/bin/env python3
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
import sys
class Example(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
hbox = QHBoxLayout(self)
qb1=QPushButton("Uncheck it")
qb2=QPushButton("Partial Check it")
qb3=QPushButton("Check it reals")
qb1.clicked.connect(self.uncheck_it)
qb2.clicked.connect(self.partial_check_it)
qb3.clicked.connect(self.check_it)
self.qch=QCheckBox("Chonk")
self.qch.stateChanged.connect(self.chonker)
self.qch.setTristate(True)
hbox.addWidget(self.qch)
hbox.addWidget(qb1)
hbox.addWidget(qb2)
hbox.addWidget(qb3)
self.setLayout(hbox)
self.move(300, 200)
self.setWindowTitle('Choooo')
self.show()
def chonker(self):
print("chonker", self.sender().text(),self.sender().checkState())
def uncheck_it(self):
self.qch.setCheckState(Qt.Unchecked)
print ("Uncheck it")
def partial_check_it(self):
self.qch.setCheckState(Qt.PartiallyChecked)
print ("Partial check it")
def check_it(self):
self.qch.setCheckState(Qt.Checked)
print ("Check it")
def main():
app = QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
if __name__ == '__main__':
main()