furas

Python - PyQt - MyCheckBox

Aug 7th, 2016
110
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.80 KB | None | 0 0
  1. #!/usr/bin/env python
  2.  
  3. #
  4. # https://www.reddit.com/r/learnpython/comments/4wkzva/pyqt_child_of_qcheckbox_with_additional_argument/
  5. #
  6.  
  7. from __future__ import print_function
  8. import sys
  9. from PyQt4 import QtGui, QtCore
  10.  
  11.  
  12. class Window(QtGui.QDialog):
  13.  
  14.     def __init__(self, window):
  15.         super(Window, self).__init__() # space after `,`
  16.         self.mw = window
  17.         self.setGeometry(50, 50, 500, 300) # space after `,`
  18.         self.setWindowTitle("PQ status!")
  19.        
  20.         self.letters_checked = [] # lower_case name  
  21.         self.all_letters = ['a','b','c','d','e'] # space after `,`  # lower_case name
  22.        
  23.         self.home()
  24.         self.show()
  25.  
  26.     def home(self):
  27.         # pythonic method to work with list
  28.         for index, letter in enumerate(self.all_letters):
  29.             self.checkBox = MyCheckBox(letter, self)
  30.             self.checkBox.stateChanged.connect(self.checkBox.add_or_remove_letter)
  31.             self.checkBox.move(20, 20*index)
  32.  
  33.  
  34. class MyCheckBox(QtGui.QCheckBox):
  35.  
  36.     def __init__(self, text, window):
  37.         self.text = text
  38.         self.window = window # add to class to use `self.window` instead of global `window`
  39.         super(MyCheckBox, self).__init__(text, window) # need parent `window/widget`
  40.  
  41.     def add_or_remove_letter(self, state):
  42.         if state == QtCore.Qt.Checked:
  43.             self.window.letters_checked.append(self.text) # with `self.`
  44.         elif self.text in self.window.letters_checked: # `test` without () # there is no `deck`
  45.             self.window.letters_checked.remove(self.text) # with `self.`
  46.            
  47.         print('[DEBUG] letters_checked:', ', '.join(self.window.letters_checked))            
  48.  
  49.  
  50. if __name__ == '__main__':
  51.     app = QtGui.QApplication(sys.argv)
  52.     GUI = Window(QtGui.QMainWindow)
  53.     app.exec_()
Add Comment
Please, Sign In to add comment