Python源码示例:PyQt5.QtGui.QMovie()
示例1
def onFinished(self):
"""图片下载完成
"""
self.loadingTimer.stop()
self.pradius = 0
reply = self.sender()
if self.isGif:
self._movie = QMovie(reply, b'gif', self)
if self._movie.isValid():
self._movie.frameChanged.connect(self._resizeGifPixmap)
self._movie.start()
else:
data = reply.readAll().data()
reply.deleteLater()
del reply
self._pixmap.loadFromData(data)
if self._pixmap.isNull():
self._pixmap = QPixmap(self.size())
self._pixmap.fill(QColor(204, 204, 204))
self._resizePixmap()
示例2
def _doDownloadImage(self, url):
# 下载图片并添加到界面
async with self.session.get(url) as resp:
data = await resp.read()
if not data:
print('下载失败: ', url)
return
path = os.path.join('tmp', os.path.basename(url))
with open(path, 'wb') as fp:
fp.write(data)
item = QListWidgetItem(url, self.listWidget)
image = QPixmap(path)
item.setSizeHint(image.size())
label = QLabel(self.listWidget)
label.setPixmap(image)
if path.endswith('.gif'): # 可能是动态图
label.setMovie(QMovie(path))
self.listWidget.setItemWidget(item, label)
self.listWidget.scrollToBottom()
示例3
def __init__(self, gui):
super(SystemTrayIcon, self).__init__()
self.gui = gui
tray_icon_path = resource(settings["application"]["tray_icon"])
self.app_pixmap = QPixmap(tray_icon_path)
self.app_icon = QIcon(tray_icon_path)
self.setIcon(self.app_icon)
self.menu = Menu(self.gui)
self.setContextMenu(self.menu)
self.activated.connect(self.on_click)
self.messageClicked.connect(self.gui.show_main_window)
self.animation = QMovie()
self.animation.setFileName(
resource(settings["application"]["tray_icon_sync"])
)
self.animation.updated.connect(self.update)
self.animation.setCacheMode(True)
示例4
def __init__(self, text="Loading..."):
super(MessageBox, self).__init__()
self.setWindowTitle("Messages")
self.setLayout(QtWidgets.QHBoxLayout())
self._layout = self.layout()
self._gif = QtWidgets.QLabel()
movie = QtGui.QMovie("loading.gif")
self._gif.setMovie(movie)
movie.start()
self._layout.addWidget(self._gif)
self._message = QtWidgets.QLabel()
self._message.setText(text)
self._layout.addWidget(self._message)
self.setObjectName('Message_Window')
示例5
def __init__(self, labelText, cancellable=True, parent=None):
super(SpinnerWidget, self).__init__(parent=parent)
self.setupUi(self)
self.movie = QtGui.QMovie(":qrc/rotator-32.gif")
self.icon.setMovie(self.movie)
self.originalLabelText = labelText
self.label.setText(labelText)
if cancellable:
self.cancelButton.clicked.connect(self.cancelled.emit)
else:
self.cancelButton.hide()
self.hide()
示例6
def get_zip_graphic(self, name):
if os.path.exists("ecu.zip"):
zf = zipfile.ZipFile("ecu.zip", "r")
zname = "graphics/" + name + ".gif"
if not zname in zf.namelist():
zname = "graphics/" + name + ".GIF"
if zname in zf.namelist():
ba = core.QByteArray(zf.read(zname))
self.buffer = core.QBuffer()
self.buffer.setData(ba)
self.buffer.open(core.QIODevice.ReadOnly)
self.img = gui.QMovie(self.buffer, 'GIF')
示例7
def initXML(self, xmldata):
text = xmldata.getAttribute("Text")
color = xmldata.getAttribute("Color")
alignment = xmldata.getAttribute("Alignment")
if text.startswith("::pic:"):
self.setScaledContents(True)
img_name = text.replace("::pic:", "").replace("\\", "/")
self.get_zip_graphic(img_name)
if self.img is None:
imgname = os.path.join(options.graphics_dir, img_name) + ".gif"
if not os.path.exists(imgname):
imgname = os.path.join(options.graphics_dir, img_name) + ".GIF"
self.img = gui.QMovie(imgname)
self.setMovie(self.img)
self.img.start()
else:
self.setText(text)
rect = getRectangleXML(getChildNodesByName(xmldata, "Rectangle")[0], self.uiscale)
qfnt = getXMLFont(xmldata, self.uiscale)
self.area = rect['width'] * rect['height']
self.setFont(qfnt)
self.resize(rect['width'], rect['height'])
self.setStyleSheet("background: %s; color: %s" % (colorConvert(color), getFontColor(xmldata)))
self.move(rect['left'], rect['top'])
if alignment == '2':
self.setAlignment(core.Qt.AlignHCenter)
elif alignment == '1':
self.setAlignment(core.Qt.AlignRight)
else:
self.setAlignment(core.Qt.AlignLeft)
示例8
def initJson(self, jsdata):
text = jsdata['text']
color = jsdata['color']
alignment = jsdata['alignment']
fontcolor = jsdata['fontcolor']
rect = jsdata['bbox']
self.area = rect['width'] * rect['height']
qfnt = jsonFont(jsdata['font'], self.uiscale)
self.ismovable = True
self.setFont(qfnt)
if text.startswith("::pic:"):
self.setScaledContents(True)
img_name = text.replace("::pic:", "").replace("\\", "/")
self.get_zip_graphic(img_name)
if self.img is None:
imgname = os.path.join(options.graphics_dir, img_name) + ".gif"
if not os.path.exists(imgname):
imgname = os.path.join(options.graphics_dir, img_name) + ".GIF"
self.img = gui.QMovie(imgname)
self.setMovie(self.img)
self.img.start()
else:
self.setText(text)
self.resize(rect['width'] / self.uiscale, rect['height'] / self.uiscale)
self.setStyleSheet("background: %s; color: %s" % (color, fontcolor))
self.move(rect['left'] / self.uiscale, rect['top'] / self.uiscale)
if alignment == '2':
self.setAlignment(core.Qt.AlignHCenter)
elif alignment == '1':
self.setAlignment(core.Qt.AlignRight)
else:
self.setAlignment(core.Qt.AlignLeft)
self.jsondata = jsdata
示例9
def _get(self, url):
"""设置图片或者请求网络图片
:param url:
"""
if not url:
self.onError('')
return
if url.startswith('http') and not self.loadingTimer.isActive():
url = QUrl(url)
request = QNetworkRequest(url)
request.setHeader(QNetworkRequest.UserAgentHeader, b'CAvatar')
request.setRawHeader(b'Author', b'Irony')
request.setAttribute(
QNetworkRequest.FollowRedirectsAttribute, True)
if qApp._network.cache():
request.setAttribute(
QNetworkRequest.CacheLoadControlAttribute, QNetworkRequest.PreferNetwork)
request.setAttribute(
QNetworkRequest.CacheSaveControlAttribute, True)
reply = qApp._network.get(request)
self.pradius = 0
self.loadingTimer.start(50) # 显示进度动画
reply.finished.connect(self.onFinished)
reply.error.connect(self.onError)
return
self.pradius = 0
if os.path.exists(url) and os.path.isfile(url):
if self.isGif:
self._movie = QMovie(url, parent=self)
if self._movie.isValid():
self._movie.frameChanged.connect(self._resizeGifPixmap)
self._movie.start()
else:
self._pixmap = QPixmap(url)
self._resizePixmap()
else:
self.onError('')
示例10
def egg(self):
self.kpos = 0
movie = QMovie(":/action/media/media.qrc")
self.ui.label.setText(None)
self.ui.label.setMovie(movie)
movie.start()
self.setStyleSheet("QDialog { background-color: red; }")
示例11
def __init__(self, filename, parent=None):
QtWidgets.QWidget.__init__(self, parent)
self.movie = QtGui.QMovie(filename)
self.movie_screen = QtWidgets.QLabel()
self.movie_screen.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
main_layout = QtWidgets.QVBoxLayout()
main_layout.addWidget(self.movie_screen)
self.setLayout(main_layout)
self.movie.setCacheMode(QtGui.QMovie.CacheAll)
self.movie.setSpeed(100)
self.movie_screen.setMovie(self.movie)
self.movie.start()
示例12
def __init__(self, *args, **kwargs):
super(ImageView, self).__init__(*args, **kwargs)
self.resize(800, 600)
layout = QHBoxLayout(self)
# 从文件加载图片
layout.addWidget(QLabel(self, pixmap=QPixmap("Data/head.jpg")))
# QResource 参考 http://doc.qt.io/qt-5/resources.html
# 从资源文件中加载1 from py file
# 转换命令pyrcc5 res.qrc -o res_rc.py
# 这种方式是从通过pyrcc5转换res.qrc为res_rc.py文件,可以直接import加载
# 此时可以通过路径:/images/head.jpg来访问
layout.addWidget(QLabel(self, pixmap=QPixmap(":/images/head.jpg")))
# 从二进制资源文件res.rcc中加载
# 转换命令tools/rcc.exe -binary res2.qrc -o res.rcc
# 这里把资源前缀修改下(/myfile),见res2.qrc文件
# 此时需要注册
QResource.registerResource("Data/res.rcc")
# 注意前缀
layout.addWidget(
QLabel(self, pixmap=QPixmap(":/myfile/images/head.jpg")))
# 从xpm数组中加载
# 通过工具tools/Image2XPM.exe来转换
# 这里把转换的xpm数组直接放到py文件中当做一个变量
# 见xpmres.py中的image_head
layout.addWidget(QLabel(self, pixmap=QPixmap(image_head)))
# 加载gif图片
movie = QMovie("Data/loading.gif")
label = QLabel(self)
label.setMovie(movie)
layout.addWidget(label)
movie.start()
示例13
def __init__(self, *args, **kwargs):
super(LoadingWidget, self).__init__(*args, **kwargs)
self.setAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
self._movie = QMovie("loading.gif")
self.setMovie(self._movie)
示例14
def __init__(self, *args, **kwargs):
super(GifSplashScreen, self).__init__(*args, **kwargs)
self.movie = QMovie('Data/splash.gif')
self.movie.frameChanged.connect(self.onFrameChanged)
self.movie.start()
示例15
def __init__(self, parent=None):
super(Delegate, self).__init__(parent=None)
self.parent = parent
self.waiting_movie = QMovie(resource("waiting.gif"))
self.waiting_movie.setCacheMode(True)
self.waiting_movie.frameChanged.connect(self.on_frame_changed)
self.sync_movie = QMovie(resource("sync.gif"))
self.sync_movie.setCacheMode(True)
self.sync_movie.frameChanged.connect(self.on_frame_changed)
示例16
def __init__(self, parent=None, repository=None, systemtray_icon=None):
"""Init window."""
super(WorkLogPreviewer, self).__init__(parent)
saveAct = QAction(QIcon(SAVE_ICON_PATH), '&Save', self)
saveAct.setShortcut('Ctrl+S')
saveAct.setStatusTip('Save work log')
saveAct.triggered.connect(self.save)
menubar = self.menuBar()
fileMenu = menubar.addMenu('&File')
fileMenu.addAction(saveAct)
self.repository = repository
self.systemtray_icon = systemtray_icon
self.statusBar()
widget = QWidget()
layout = QVBoxLayout()
self.te = QPlainTextEdit()
layout.addWidget(self.te)
self.lbl = QLabel()
self.lbl.hide()
self.movie = QMovie(LOADER_PATH)
self.lbl.setMovie(self.movie)
hlayout = QHBoxLayout()
hlayout.addStretch()
hlayout.addWidget(self.lbl)
hlayout.addStretch()
layout.addLayout(hlayout)
self.generate_log()
widget.setLayout(layout)
widget.setFixedSize(500, 500)
self.setCentralWidget(widget)
self.setWindowTitle(f'Work log for {repository.full_name}')
self.setWindowIcon(QIcon(ICON_PATH))
self.setLocale(QtCore.QLocale())
self.adjustSize()
self.setStyleSheet(qdarkstyle.load_stylesheet_pyqt5())
示例17
def __init__(self, parent=None):
"""Init widget."""
super(MainWidget, self).__init__(parent)
layout = QVBoxLayout()
self.parent = parent
self.ght = QLineEdit()
self.ght.setPlaceholderText("Github Token")
self.ght_keyPressEvent = self.ght.keyPressEvent
self.ght_original_style = self.ght.styleSheet()
self.ght.keyPressEvent = self.line_keyPressEvent
layout.addWidget(self.ght)
self.btn = QPushButton("Connect to github")
self.btn.clicked.connect(self.getRepos)
layout.addWidget(self.btn)
self.combo = QComboBox()
self.combo.setDisabled(True)
layout.addWidget(self.combo)
self.btn_save = QPushButton("Open worklog")
self.btn_save.setDisabled(True)
self.btn_save.clicked.connect(self.open_log)
layout.addWidget(self.btn_save)
self.lbl = QLabel()
self.lbl.hide()
self.movie = QMovie(LOADER_PATH)
self.lbl.setMovie(self.movie)
hlayout = QHBoxLayout()
hlayout.addStretch()
hlayout.addWidget(self.lbl)
hlayout.addStretch()
layout.addLayout(hlayout)
self.setLayout(layout)
self.setLocale(QtCore.QLocale())
self.sig.connect(self.add_repo_to_combobox)
示例18
def __init__(self, file_in, action, action_type, parent=None):
super(Install, self).__init__(parent)
self.setMinimumSize(400, 100)
self.file_in = file_in
self.setWindowTitle("Working...")
self.buttonCancel = QPushButton()
self.buttonCancel.setText("Cancel")
self.buttonCancel.clicked.connect(self.cancel)
self.progress = QProgressBar()
self.progress2 = QProgressBar()
self.progress2.setVisible(False)
self.lbl1 = QLabel()
gif = os.path.abspath("/usr/lib/resetter/data/icons/chassingarrows.gif")
self.movie = QtGui.QMovie(gif)
self.movie.setScaledSize(QtCore.QSize(20, 20))
self.pixmap = QtGui.QPixmap("/usr/lib/resetter/data/icons/checkmark.png")
self.pixmap2 = self.pixmap.scaled(20, 20)
verticalLayout = QVBoxLayout(self)
verticalLayout.addWidget(self.lbl1)
verticalLayout.addWidget(self.progress)
verticalLayout.addWidget(self.progress2)
gridLayout = QGridLayout()
self.labels = {}
for i in range(1, 3):
for j in range(1, 3):
self.labels[(i, j)] = QLabel()
self.labels[(i, j)].setMinimumHeight(20)
gridLayout.addWidget(self.labels[(i, j)], i, j)
gridLayout.setAlignment(QtCore.Qt.AlignCenter)
self.labels[(1, 2)].setText("Loading packages")
self.labels[(2, 2)].setText(action)
verticalLayout.addSpacing(20)
verticalLayout.addLayout(gridLayout)
verticalLayout.addWidget(self.buttonCancel, 0, QtCore.Qt.AlignRight)
self.logger = logging.getLogger(__name__)
self.logger.setLevel(logging.DEBUG)
handler = logging.FileHandler('/var/log/resetter/resetter.log')
handler.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(funcName)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)
self.logger.addHandler(handler)
self.installProgress = ProgressThread(file_in, action_type)
self.installProgress.start_op1.connect(self.updateProgressBar)
self.installProgress.aprogress.run_op.connect(self.updateProgressBar2)
self.installProgress.iprogress.run_op.connect(self.updateProgressBar2)
self.installProgress.start_op.connect(self.showError)
self.start()
示例19
def __init__(self, file_in, parent=None):
super(Apply, self).__init__(parent)
self.setMinimumSize(400, 250)
self.file_in = file_in
self.setWindowTitle("Applying")
self.error_msg = QMessageBox()
self.error_msg.setIcon(QMessageBox.Critical)
self.error_msg.setWindowTitle("Error")
self.buttonCancel = QPushButton()
self.buttonCancel.setText("Cancel")
self.buttonCancel.clicked.connect(self.finished)
self.progress = QProgressBar()
self.progress2 = QProgressBar()
self.progress2.setVisible(False)
self.lbl1 = QLabel()
gif = os.path.abspath("/usr/lib/resetter/data/icons/chassingarrows.gif")
self.movie = QtGui.QMovie(gif)
self.movie.setScaledSize(QtCore.QSize(20, 20))
self.pixmap = QtGui.QPixmap("/usr/lib/resetter/data/icons/checkmark.png")
self.pixmap2 = self.pixmap.scaled(20, 20)
verticalLayout = QVBoxLayout(self)
verticalLayout.addWidget(self.lbl1)
verticalLayout.addWidget(self.progress)
verticalLayout.addWidget(self.progress2)
gridLayout = QGridLayout()
self.labels = {}
for i in range(1, 7):
for j in range(1, 3):
self.labels[(i, j)] = QLabel()
self.labels[(i, j)].setMinimumHeight(20)
gridLayout.addWidget(self.labels[(i, j)], i, j)
gridLayout.setAlignment(QtCore.Qt.AlignCenter)
self.labels[(1, 2)].setText("Loading packages")
self.labels[(2, 2)].setText("Removing packages")
self.labels[(3, 2)].setText("Cleaning Up")
self.labels[(4, 2)].setText("Installing packages")
self.labels[(5, 2)].setText("Deleting Users")
verticalLayout.addSpacing(20)
verticalLayout.addLayout(gridLayout)
verticalLayout.addWidget(self.buttonCancel, 0, QtCore.Qt.AlignRight)
self.logger = logging.getLogger(__name__)
self.logger.setLevel(logging.DEBUG)
handler = logging.FileHandler('/var/log/resetter/resetter.log')
handler.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(funcName)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)
self.logger.addHandler(handler)
self.progressView = ProgressThread(self.file_in, False)
self.progressView.start_op1.connect(self.updateProgressBar)
self.progressView.aprogress.run_op.connect(self.updateProgressBar2)
self.progressView.iprogress.run_op.connect(self.updateProgressBar2)
self.progressView.start_op.connect(self.showError)
self.addUser()
self.start()
示例20
def __init__(self, parent=None, repository=None, systemtray_icon=None):
"""Init window."""
super(WorkLogPreviewer, self).__init__(parent)
saveAct = QAction(QIcon(SAVE_ICON_PATH), '&Save', self)
saveAct.setShortcut('Ctrl+S')
saveAct.setStatusTip('Save work log')
saveAct.triggered.connect(self.save)
menubar = self.menuBar()
fileMenu = menubar.addMenu('&File')
fileMenu.addAction(saveAct)
self.repository = repository
self.systemtray_icon = systemtray_icon
self.statusBar()
widget = QWidget()
layout = QVBoxLayout()
self.te = QPlainTextEdit()
layout.addWidget(self.te)
self.lbl = QLabel()
self.lbl.hide()
self.movie = QMovie(LOADER_PATH)
self.lbl.setMovie(self.movie)
hlayout = QHBoxLayout()
hlayout.addStretch()
hlayout.addWidget(self.lbl)
hlayout.addStretch()
layout.addLayout(hlayout)
self.generate_log()
widget.setLayout(layout)
widget.setFixedSize(500, 500)
self.setCentralWidget(widget)
self.setWindowTitle(f'Work log for {repository.full_name}')
self.setWindowIcon(QIcon(ICON_PATH))
self.setLocale(QtCore.QLocale())
self.adjustSize()
self.setStyleSheet(qdarkstyle.load_stylesheet_pyqt5())
示例21
def __init__(self, parent=None):
"""Init widget."""
super(MainWidget, self).__init__(parent)
layout = QVBoxLayout()
self.parent = parent
self.ght = QLineEdit()
self.ght.setPlaceholderText("Github Token")
self.ght_keyPressEvent = self.ght.keyPressEvent
self.ght_original_style = self.ght.styleSheet()
self.ght.keyPressEvent = self.line_keyPressEvent
layout.addWidget(self.ght)
self.btn = QPushButton("Connect to github")
self.btn.clicked.connect(self.getRepos)
layout.addWidget(self.btn)
self.combo = QComboBox()
self.combo.setDisabled(True)
layout.addWidget(self.combo)
self.btn_save = QPushButton("Open worklog")
self.btn_save.setDisabled(True)
self.btn_save.clicked.connect(self.open_log)
layout.addWidget(self.btn_save)
self.lbl = QLabel()
self.lbl.hide()
self.movie = QMovie(LOADER_PATH)
self.lbl.setMovie(self.movie)
hlayout = QHBoxLayout()
hlayout.addStretch()
hlayout.addWidget(self.lbl)
hlayout.addStretch()
layout.addLayout(hlayout)
self.setLayout(layout)
self.setLocale(QtCore.QLocale())
self.sig.connect(self.add_repo_to_combobox)