Python3 PyQt4 Creating a simple QCheckBox and changing a Boolean variable

痴心易碎 提交于 2019-12-30 11:29:07

问题


So I have been trying to write a GUI using Python 3.3 and PyQt4. 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. 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. Been working on this pretty much an entire day and none of the tutorials have been much help.


回答1:


The checkbox emits a stateChanged event when its state is changed (really!). 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_())



回答2:


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()


来源:https://stackoverflow.com/questions/12736825/python3-pyqt4-creating-a-simple-qcheckbox-and-changing-a-boolean-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!