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

时间:2019-10-03 19:50:27

标签: python pyqt pyqt5 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_())

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

1 个答案:

答案 0 :(得分:3)

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

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