PyQt5 – 使用方向键在窗口中移动标签位置
在这篇文章中,我们将看到如何使用箭头键在窗口中移动标签,即当按下箭头键(方向键)时,标签将向该方向移动。例如,当用户按下向上的方向键时,标签会向上移动,同样,其他方向键的标签也会改变其位置。
概念: 我们可以通过增加/减少标签的坐标值来改变标签的位置,但如果标签到达任何一端,则不增加或减少,下面是每个方向键被按下时的数据。
When Up arrow key is pressed : X Co-ordinate remain same, decrement the Y Co-ordinate
When Down arrow key is pressed : X Co-ordinate remain same, increment the Y Co-ordinate
When Left arrow key is pressed : Decrement X Co-ordinate, Y Co-ordinate remain same
When Right arrow key is pressed : Increment X Co-ordinate, Y Co-ordinate remain same
Python
下面是边缘的限制数据,以便标签保持在窗口中。
对于顶部边缘,y坐标应始终大于0
对于底部边缘,y坐标应始终小于窗口的高度–标签的高度
对于左侧边缘,x坐标应始终大于0
对于右侧边缘,x坐标应始终小于窗口的宽度–标签的宽度
实施步骤:
1.创建一个主窗口
2.在主窗口内创建一个标签
3.为标签添加样式表的几何图形
4.创建一个速度变量
5.覆盖按键事件
6.在按键事件中获取标签的当前x和y坐标
7.检查哪个键被按下,并检查是否没有到达边端,然后在移动方法的帮助下通过增加/减少速度值来更新x和y坐标。
以下是实现的过程
# importing libraries
from PyQt5.QtWidgets import *
from PyQt5 import QtCore, QtGui
from PyQt5.QtGui import *
from PyQt5.QtCore import *
import sys
class Window(QMainWindow):
def __init__(self):
super().__init__()
# setting title
self.setWindowTitle("Python ")
# width of window
self.w_width = 500
# height of window
self.w_height = 500
# setting geometry
self.setGeometry(100, 100, self.w_width, self.w_height)
# calling method
self.UiComponents()
# showing all the widgets
self.show()
# speed variable
self.speed = 15
# method for components
def UiComponents(self):
# creating a label
self.label = QLabel(self)
# label width
self.l_width = 40
# label height
self.l_height = 40
# setting geometry to the label
self.label.setGeometry(200, 200, self.l_width, self.l_height)
# setting stylesheet to the label
self.label.setStyleSheet("QLabel"
"{"
"border : 4px solid darkgreen;"
"background : lightgreen;"
"}")
# override the key press event
def keyPressEvent(self, event):
# get the current co-ordinates of the label
# X Co-ordinate
x = self.label.x()
# Y Co-ordinate
y = self.label.y()
# if up arrow key is pressed
if event.key() == Qt.Key_Up:
# if top position is attained
if y > 0:
self.label.move(x, y - self.speed)
# if down arrow key is pressed
elif event.key() == Qt.Key_Down:
# if bottom position is attained
# for bottom point, bottom co-ordinate will be
# height of window - height of label
if y < self.w_height - self.l_height:
self.label.move(x, y + self.speed)
# if left arrow key is pressed
elif event.key() == Qt.Key_Left:
# if left end position is attained
if x > 0:
self.label.move(x - self.speed, y)
# if down arrow key is pressed
elif event.key() == Qt.Key_Right:
# if right end position is attained
# for right end point, right co-ordinate will be
# width of window - width of label
if x < self.w_width - self.l_width:
self.label.move(x + self.speed, y)
# create pyqt5 app
App = QApplication(sys.argv)
# create the instance of our Window
window = Window()
# start the app
sys.exit(App.exec())
Python