PyQt5 – 如何获得标签坐标
PyQt5的主窗口就像一个图形,它有x轴和y轴,所有的小部件都是根据它们的x、y坐标来定位的。当我们创建标签时,标签是在左上角形成的,左上角的坐标是(0, 0),我们可以用move()方法移动标签。
在这篇文章中,我们将看到如何获得标签的坐标。为了做到这一点,我们将使用x()方法获取x坐标,使用y()方法获取y坐标。
语法:
x_position = label.x()
y_position =label.y()
参数: 两个方法都不需要参数。
返回: 两者都返回整数。
代码。
# importing the required libraries
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
import sys
class Window(QMainWindow):
def __init__(self):
super().__init__()
# set the title
self.setWindowTitle("Python")
# setting the geometry of window
self.setGeometry(60, 60, 600, 400)
# creating a label widget
self.label_1 = QLabel(self)
# moving position
self.label_1.move(100, 100)
# setting up the border
self.label_1.setStyleSheet("border :3px solid blue;")
# getting x and y co-ordinates
x = str(self.label_1.x())
y = str(self.label_1.y())
# setting label text
self.label_1.setText(x+", "+ y)
# creating a label widget
self.label_2 = QLabel(self)
# moving position
self.label_2.move(160, 170)
# setting up the border
self.label_2.setStyleSheet("border :3px solid yellow;")
# getting x and y co-ordinates
x = str(self.label_2.x())
y = str(self.label_2.y())
# setting label text
self.label_2.setText(x + ", " + y)
# show all the widgets
self.show()
# create pyqt5 app
App = QApplication(sys.argv)
# create the instance of our Window
window = Window()
# start the app
sys.exit(App.exec())
输出 :