有没有办法知道 QGridLayout 中元素的 X 和 Y 坐标?

Is there a way to know the X and Y coordinates of an element in a QGridLayout?

我有一个 QGridLayout,我要在其中添加不同的元素,我需要知道这些元素,我需要知道特定元素的坐标。有没有办法做到这一点? 我阅读了文档并尝试使用 pos() 和 geometry() 属性,但我无法得到我想要的。 例如,给定以下代码:

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

class basicWindow(QWidget):
    def __init__(self):
        super().__init__()
        grid_layout = QGridLayout()
        self.setLayout(grid_layout)

        for x in range(3):
            for y in range(3):
                button = QPushButton(str(str(3*x+y)))
                grid_layout.addWidget(button, x, y)

        self.setWindowTitle('Basic Grid Layout')

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

有没有办法知道每个按钮的坐标?

几何图形仅在显示小部件时更新,因此您可能在显示之前打印了坐标。在下面的示例中,如果您按任何按钮,它将打印相对于 window.

的坐标
import sys
from PyQt5.QtCore import pyqtSlot
from PyQt5.QtWidgets import QWidget, QGridLayout, QPushButton, QApplication


class BasicWindow(QWidget):
    def __init__(self):
        super().__init__()
        grid_layout = QGridLayout(self)

        for x in range(3):
            for y in range(3):
                button = QPushButton(str(3 * x + y))
                button.clicked.connect(self.on_clicked)
                grid_layout.addWidget(button, x, y)

        self.setWindowTitle("Basic Grid Layout")

    @pyqtSlot()
    def on_clicked(self):
        button = self.sender()
        print(button.text(), ":", button.pos(), button.geometry())


if __name__ == "__main__":
    app = QApplication(sys.argv)
    windowExample = BasicWindow()
    windowExample.show()
    sys.exit(app.exec_())

输出:

0 : PyQt5.QtCore.QPoint(10, 10) PyQt5.QtCore.QRect(10, 10, 84, 34)
4 : PyQt5.QtCore.QPoint(100, 50) PyQt5.QtCore.QRect(100, 50, 84, 34)
8 : PyQt5.QtCore.QPoint(190, 90) PyQt5.QtCore.QRect(190, 90, 84, 34)

更新:

如果要在给定行和列的情况下获取小部件的位置,首先要获取 QLayoutItem,并且必须从该 QLayoutItem 获取小部件。在下面的示例中,按钮的位置在 window 显示后立即打印:

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


class basicWindow(QWidget):
    def __init__(self):
        super().__init__()
        grid_layout = QGridLayout(self)

        for x in range(3):
            for y in range(3):
                button = QPushButton(str(3 * x + y))
                grid_layout.addWidget(button, x, y)

        self.setWindowTitle("Basic Grid Layout")

        QTimer.singleShot(0, lambda: self.print_coordinates(1, 1))

    def print_coordinates(self, x, y):
        grid_layout = self.layout()
        it = grid_layout.itemAtPosition(x, y)
        w = it.widget()
        print(w.pos())



if __name__ == "__main__":
    app = QApplication(sys.argv)
    windowExample = basicWindow()
    windowExample.show()
    sys.exit(app.exec_())