问题描述
我正在制作一个python项目,我正在使用pyqt。目的是显示一张图片(我使用的是pixmap),我希望这张图片的任何一列像素根据时间随机下降。目的是创造一种“溶解”屏幕的效果。
这是我的代码:
#-*- coding: utf-8 -*-
# ---------- Imports ----------
import sys,time,os,random
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
# ---------- Main ----------
class Ui (QMainWindow):
def __init__(self):
QWidget.__init__(self)
# ----- Fichiers -----
folder_path = os.path.dirname(os.path.abspath(__file__))
self.picture_path = str(folder_path + '\\solar_wallpaper.jpg')
self.icon_path = str(folder_path + '\\solar_icon.ico')
# ----- Configuration de la fenêtre -----
self.setwindowFlags(self.windowFlags() &~ Qt.WindowCloseButtonHint)
self.setwindowFlags(self.windowFlags() &~ Qt.WindowMinimizeButtonHint)
self.setwindowFlags(self.windowFlags() &~ Qt.WindowMaximizeButtonHint)
self.setwindowTitle('Solar')
self.setwindowIcon(QIcon(self.icon_path))
self.setStyleSheet("background-color: black;")
# ----- Appel des méthodes -----
self.init_components()
self.init_layout()
self.showFullScreen()
def init_components (self):
self.setCentralWidget(qgroupbox())
self.picture = QLabel(self)
self.picture.setScaledContents(True)
self.picture.setpixmap(Qpixmap(self.picture_path))
self.picture.setAlignment(Qt.AlignCenter)
colonne = self.picture.width()
for i in range (colonne):
None
def init_layout (self):
self.layout = QVBoxLayout()
self.layout.addWidget(self.picture)
self.centralWidget().setLayout(self.layout)
# ---------- Launcher ----------
app = QApplication.instance()
if not app :
app = QApplication(sys.argv)
ui = Ui()
app.exec()
解决方法
一种可能的解决方案是复制和粘贴矩形块,但具有垂直距离:
import random
import sys
from PyQt5.QtCore import QRect,QTimer
from PyQt5.QtGui import QColor,QPainter,QPixmap
from PyQt5.QtWidgets import QApplication,QLabel
COLUMN_WIDTH = 10
DELTA = 10
def build_pixmap():
delta = 20
pixmap = QPixmap(512,512)
pixmap.fill(QColor("blue"))
painter = QPainter(pixmap)
for i in range(5,15):
dt = i * delta
r = QRect(pixmap.rect().adjusted(0,dt,-dt))
color = QColor(*random.sample(range(255),3))
painter.fillRect(r,color)
painter.end()
return pixmap
def aply_effect(pixmap,number_of_columns):
i = round(pixmap.width() / COLUMN_WIDTH)
for _ in range(number_of_columns):
j = random.randint(0,i)
rect = QRect(j * COLUMN_WIDTH,COLUMN_WIDTH,pixmap.height())
pix = pixmap.copy(rect)
painter = QPainter(pixmap)
painter.drawPixmap(rect.translated(0,DELTA),pix)
painter.end()
return pixmap
def main():
app = QApplication(sys.argv)
pixmap_demo = build_pixmap()
label = QLabel(pixmap=pixmap_demo)
label.show()
def on_timeout():
out_pixmap = aply_effect(label.pixmap(),40)
label.setPixmap(out_pixmap)
timer = QTimer(interval=40,timeout=on_timeout)
timer.start()
app.exec_()
if __name__ == "__main__":
main()