popuban
popuban

Reputation: 81

PyQt : Widget and PushButtons

Using PyQt, I want to create an user interface which answers to this set of rules :

The main issue I have is that I do not find any Qt command to access the push button at a predefined position in the grid. What I found which is the closest from this is the function mouseClickEvent. Sadly, QtGui.QGridLayout.itemAtPosition(self.grid,*location).setEnabled(False) does not work, because QtGui.QGridLayout.itemAtPosition(self.grid,*location) is not a PushButton, but a QtWidget.

There is some pseudo-code below : it is written after a #.

import sys
import numpy as np
from PyQt4 import QtGui

class InterfaceGraphique(QtGui.QWidget):

    def __init__(self,size):
        super(InterfaceGraphique, self).__init__()
        self.size=size
        self.position=((size-1)//2,(size-1)//2)
        self.initUI(size)

    def initUI(self,size):
        self.grid = QtGui.QGridLayout()
        self.setLayout(self.grid)
        names=list(map(lambda x: str(x),np.random.choice(10,size**2)))
        positions = [(i, j) for i in range(size) for j in range(size)]
        for position, name in zip(positions, names):
            button = QtGui.QPushButton(name)
            button.clicked.connect(self.mouseClickEvent)
            self.grid.addWidget(button, *position)
        self.move(300, 150)
        self.setWindowTitle('Game')
        self.show()
    def mouseClickEvent(self):
        button=self.sender()
        idx = self.grid.indexOf(button)
        location = self.grid.getItemPosition(idx)
#       QtGui.QGridLayout.itemAtPosition(self.grid,*location).setEnabled(False)
#       for neighbor in neighbors(location)
    #           QtGui.QGridLayout.itemAtPosition(self.grid,*neighbor).setEnabled(True)
        self.position=location


size=5
def main():
    app = QtGui.QApplication(sys.argv)
    ex = InterfaceGraphique(size)
    app.exec_()

if __name__ == '__main__':
    main()

Upvotes: 1

Views: 671

Answers (1)

three_pineapples
three_pineapples

Reputation: 11849

Assuming that neighbours does what you want (you haven't included that bit of code), you want to call setEnabled() on the widget of the QWidgetItem.

self.grid.itemAtPosition(*neighbour).widget().setEnabled(True)

Upvotes: 2

Related Questions