python - 有没有办法知道 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_())
有没有办法知道每个按钮的坐标?
解决方案
几何图形仅在显示小部件时更新,因此您可能在显示坐标之前打印坐标。在下面的示例中,如果您按下任何按钮,它将打印相对于窗口的坐标。
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_())
推荐阅读
- asp.net-core - ASP.NET Core 不存在的静态文件请求解析为回退
- c++ - const T& rf = lvalue of T 是身份转换吗?
- c# - 从 List.FindAll 创建新的派生类对象
- python - RuntimeError:预期的标量类型 Long 但在损失中找到 Int = 标准(输出,y_train)
- jquery - 我可以突出显示特定的日子吗?比如 datepicker js 中的所有星期一星期二等
- python - 检查列表中是否存在至少一个字符串
- vue.js - 我们如何使用 vuetify-data-table 根据屏幕截图进行设计
- flutter - 将获取请求正文同步分配给变量 - Dart
- google-chrome - 加载网站时出现 HTTP2 协议错误
- biztalk - BizTalk 2013 R2 - 基于速率的泛滥消息限制