首页 > 解决方案 > 有没有办法知道 QGridLayout 中元素的 X 和 Y 坐标?

问题描述

我有一个 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_())

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

标签: pythonpyqtpyqt5qgridlayout

解决方案


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

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 中获取小部件。在下面的例子中,一个按钮的位置在窗口显示之后被打印出来:

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_())

推荐阅读