I am trying to get a ball(QPixmap inside a QLabel) to rotate while bouncing off the edges of the screen. But the ball, even though it does rotate seems to be moving along the axis inside the QLabel so after a few movements of the timer it moves outside the borders of the QLabel and therefore does not appear any longer.
Please see my code below.
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
import random
x = 0
y = 00
velX = 2
velY = 1
randX = random.choice([1, 2, 3])
randY = random.choice([1, 2, 3])
class MainWindow(QMainWindow):
def __init__(self, *args, **kwargs):
super(MainWindow, self).__init__(*args, **kwargs)
self.setWindowTitle('ball move')
self.setMinimumWidth(800)
self.setMaximumWidth(800)
self.setMinimumHeight(500)
self.setMaximumHeight(500)
self.setStyleSheet('background-color: black;border:none;')
self.ballLabel = QLabel(self)
self.ballPixmap = QPixmap('ball.png')
self.resizedBallPixmap = self.ballPixmap.scaled(50, 50, Qt.KeepAspectRatio, Qt.FastTransformation)
self.ballLabel.setFixedSize(50, 50)
self.ballRotation = 10
self.ballLabel.setPixmap(self.resizedBallPixmap)
self.ballLabel.setStyleSheet('border:1px solid red;')
self.ballLabel.show()
self.ballLabel.move(0, 0)
def rotateBall(self):
self.resizedBallPixmap = self.resizedBallPixmap.transformed(
QTransform().rotate(self.ballRotation), Qt.SmoothTransformation)
# self.resizedBallPixmap = self.resizedBallPixmap.transformed(QTransform().translate(self.resizedBallPixmap.size().width()/2, self.resizedBallPixmap.size().height()/2))
self.ballLabel.setPixmap(self.resizedBallPixmap)
def ballMove():
global x, y, velX, velY, randX, randY
if (main_window.ballLabel.pos().x() + 50) > 800:
velX = -1
randX = random.choice([1, 2, 3])
randY = random.choice([1, 2, 3])
elif main_window.ballLabel.pos().x() < 0:
velX = 1
randX = random.choice([1, 2, 3])
randY = random.choice([1, 2, 3])
elif (main_window.ballLabel.pos().y() + 50) > 500:
velY = -1
randX = random.choice([1, 2, 3])
randY = random.choice([1, 2, 3])
elif main_window.ballLabel.pos().y() < 0:
velY = 1
randX = random.choice([1, 2, 3])
randY = random.choice([1, 2, 3])
x += velX*randX
y += velY*randY
main_window.rotateBall()
main_window.ballLabel.move(x, y)
if __name__ == "__main__":
app = QApplication([])
main_window = MainWindow()
main_window.show()
timer = QTimer()
timer.timeout.connect(ballMove)
timer.start(1000)
app.exec_()