[英]Python3 PyQt4 Creating a simple QCheckBox and changing a Boolean variable
So I have been trying to write a GUI using Python 3.3 and PyQt4. 因此,我一直在尝试使用Python 3.3和PyQt4编写GUI。 I have been through a few tutorials and I still can't figure out how to have a Checkbox checking and unchecking trigger change in a global variable.
我已经看过一些教程,但仍然想不通如何让Checkbox选中和取消选中全局变量中的触发器更改。 I can't get it to trigger anything for that matter because all the tutorials use methods that wont work for me.
由于所有教程都使用对我不起作用的方法,因此我无法触发任何事情。
The program is too big to copy here as a whole so I have put together the basic structure of the program surrounding the Checkboxes 该程序太大,无法在此处整体复制,因此我将“复选框”周围的程序的基本结构组合在一起
import sys
from PyQt4 import QtGui, QtCore
ILCheck = False
class SelectionWindow(QtGui.QWidget):
def __init__(self, parent=None):
super(SelectionWindow, self).__init__(parent)
ILCheckbox = QtGui.QCheckBox(self)
ILCheckbox.setCheckState(QtCore.Qt.Unchecked)
MainLayout = QtGui.QGridLayout()
MainLayout.addWidget(ILCheckbox, 0, 0, 1, 1)
self.setLayout(MainLayout)
This is where I'm stuck. 这就是我卡住的地方。 What I want to do is change the state of ILCheck to True if the ILCheckbox is Checked and change it back to False when its Unchecked.
我想做的是,如果选中了ILCheckbox,则将ILCheck的状态更改为True,如果未选中,则将其更改回False。 Been working on this pretty much an entire day and none of the tutorials have been much help.
整整一天都在工作,而这些教程都没有太大帮助。
The checkbox emits a stateChanged
event when its state is changed (really!). 当复选框的状态更改时(真的!),该复选框会发出
stateChanged
事件。 Connect it to an event handler: 将其连接到事件处理程序:
import sys
from PyQt4.QtGui import *
from PyQt4.QtCore import *
class SelectionWindow(QMainWindow):
def __init__(self, parent=None):
super().__init__(parent)
self.ILCheck = False
ILCheckbox = QCheckBox(self)
ILCheckbox.setCheckState(Qt.Unchecked)
ILCheckbox.stateChanged.connect(self.ILCheckbox_changed)
MainLayout = QGridLayout()
MainLayout.addWidget(ILCheckbox, 0, 0, 1, 1)
self.setLayout(MainLayout)
def ILCheckbox_changed(self, state):
self.ILCheck = (state == Qt.Checked)
print(self.ILCheck)
if __name__ == '__main__':
app = QApplication(sys.argv)
window = SelectionWindow()
window.show()
sys.exit(app.exec_())
Try to avoid using a global variables. 尽量避免使用全局变量。
Instead, make the checkbox an attribute of the window and test its state directly: 相反,将复选框设置为窗口的属性,然后直接测试其状态:
class SelectionWindow(QtGui.QWidget):
def __init__(self, parent=None):
super(SelectionWindow, self).__init__(parent)
self.ILCheckbox = QtGui.QCheckBox(self)
self.ILCheckbox.setChecked(QtCore.Qt.Unchecked)
MainLayout = QtGui.QGridLayout()
MainLayout.addWidget(self.ILCheckbox, 0, 0, 1, 1)
self.setLayout(MainLayout)
...
window = SelectionWindow()
print window.ILCheckbox.isChecked()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.