I'm trying to use a loop to create multiple Checkboxes. I'd like to be able to convert this grid of boxes to make a numpy array. The code manually creates a 5x5 matrix of checkboxes, corresponding to the same point in the numpy array. When this code is run and boxes are checked by the user, the numpy array alaways prints as such:
[[False False False False False]
[False False False False False]
[False False False False False]
[False False False False False]
[False False False False True]]
I really don't know what's wrong.
import sys
from PyQt5.QtWidgets import (QWidget, QApplication, QPushButton, QCheckBox)
from PyQt5.QtCore import Qt
import numpy as np
class Example(QWidget):
def __init__(self):
super().__init__()
self.grid =np.zeros([5,5], dtype=bool)
self.x_pos, self.y_pos = 0, 0
self.initUI()
def initUI(self):
for i in range(5):
for j in range(5):
self.x_pos, self.y_pos = i, j
btn = QCheckBox(self)
btn.move(50+17*i, 50+17*j)
# btn.toggle()
btn.stateChanged.connect(self.click)
done = QPushButton('Done', self)
done.clicked.connect(self._print)
self.setGeometry(300, 300, 300, 200)
self.show()
def click(self, state):
if state == Qt.Checked:
self.grid[self.x_pos][self.y_pos] = True
else:
self.grid[self.x_pos][self.y_pos] = False
def _print(self):
print(self.grid)
self.x_posandself.y_posis changed whileinitUI()is running, but after that you don't change the variable. Therefore, those 2 variables stay[5,5]and only the element in that position changes. You should assign the number that can track down the position of actual checkbox to those 2 variables.