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

问题描述 投票:0回答:1

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

是否可以了解每个按钮的坐标?

python pyqt pyqt5 qgridlayout
1个回答
0
投票

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

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)
© www.soinside.com 2019 - 2024. All rights reserved.