【问题标题】:PyQt - get row and column of clicked button in gridPyQt - 获取网格中单击按钮的行和列
【发布时间】:2020-10-06 07:42:22
【问题描述】:

我正在使用 PyQt 开发扫雷应用程序并遇到问题,如何在网格布局中返回单击按钮的行和列?下面是尽可能少的示例来演示该问题。我的代码总是返回最后一行和最后一列,我不知道如何修复它。我尝试过的其他事情是使用 2D 列表,但仍然无法正常工作。

from PyQt5 import QtWidgets, QtCore, QtGui
import sys


class ApplicationWindow(QtWidgets.QWidget):

def __init__(self, size):
    super(ApplicationWindow, self).__init__()
    self.setGeometry(0, 0, 600, 400)
    self.setWindowTitle('MineSweeper')
    self.size = size
    self.grid_layout = QtWidgets.QGridLayout()   
    self.grid_layout.setSpacing(0)
    self.create_grid(self.size)
    self.setLayout(self.grid_layout)

def create_grid(self):        
    for row in range(self.size):
        for col in range(self.size):
            grid_button = QtWidgets.QPushButton()
            grid_button.clicked.connect(lambda: self.tell_me(row, col))
            grid_button.setFixedSize(30, 30)
            grid_button.setStyleSheet('background-color : rgba(0, 0, 0, 100); border :1px solid rgba(0, 0, 0, 150)')
            self.grid_layout.addWidget(grid_button, row, col)

def tell_me(self, row, col):
    print(row, col)


if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    window = ApplicationWindow(10)
    window.show()
    sys.exit(app.exec())

更新: 所以我设法返回了正确的列数,但是当我更改 lambda 函数时,我的行数一直为 False

grid_button.clicked.connect(lambda r=row, c=col: self.tell_me(r, c))

【问题讨论】:

    标签: python python-3.x pyqt pyqt5 minesweeper


    【解决方案1】:

    clicked 信号始终有一个用于检查状态的 bool 参数,您也必须在 lambda 中考虑这一点,因为它是用于第一个参数的。

    grid_button.clicked.connect(lambda _, r=row, c=col: self.tell_me(r, c))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-02
      • 1970-01-01
      • 2014-04-24
      • 2012-10-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多