A
A
Andreyyyyyyyyy2019-12-26 08:00:24
Python
Andreyyyyyyyyy, 2019-12-26 08:00:24

How to solve problem with Python + PyQT Designer interaction?

Hello, I am writing a tic-tac-toe game in python using PyQt as an external interface, and more specifically QT Designer. In the designer, I created a 9x9 field using buttons and ran into the following problem: I can call a function when a specific button is pressed, each button has its own name, so in order for the field to respond to clicks, I need to register a function call for pressing each button and a new function for these clicks, it is rather problematic to do this with a 9x9 field. How to make the script respond to pressing any button and call a common function, then determine the cell in the field by the name of the button without writing an action script for each of the buttons. Is there another way to implement this idea?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
Ronald McDonald, 2019-12-26
@Zoominger

There is.
You generate buttons in the code, loop on each connect and the desired action, defining the pressed button through QObjectName.
Read about QSignalMapper, it might help.

B
bbkmzzzz, 2019-12-26
@bbkmzzzz

That is, was it too lazy to add 91 buttons with your hands?)
Somehow you can:

import sys
from PyQt5.QtWidgets import QApplication, QWidget, QGridLayout, QPushButton


class Main(QWidget):
    def __init__(self):
        super(Main, self).__init__()

        # список в котором будут кнопки
        self.buttons = []

        #  компоновщик "сетка"
        self.grid = QGridLayout()
        self.setLayout(self.grid)

        for row in range(9):
            for column in range(9):
                btn = QPushButton()
                #
                btn.setObjectName(f'QPushButton_{row}_{column}')
                self.buttons.append(btn)

                #  добавляем кнопку на сетку в позицию строка, столбец
                self.grid.addWidget(btn, row, column)

                #  связываем сигнал со слотом
                btn.clicked.connect(self._onButtonClick)

    def _onButtonClick(self):
        #  self.sender() - то, что породило сигнал
        print(f'click on {self.sender().objectName()} button')


if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = Main()
    ex.show()
    sys.exit(app.exec_())

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question