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