class Delegate(QStyledItemDelegate): 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) def on_frame_changed(self): values = self.parent.model().status_dict.values() if 0 in values or 1 in values or 99 in values: self.parent.viewport().update() else: self.waiting_movie.setPaused(True) self.sync_movie.setPaused(True) def paint(self, painter, option, index): column = index.column() if column == 1: pixmap = None status = index.data(Qt.UserRole) if not status: # "Loading..." self.waiting_movie.setPaused(False) pixmap = self.waiting_movie.currentPixmap().scaled(20, 20) elif status in (1, 99): # "Syncing", "Scanning" self.sync_movie.setPaused(False) pixmap = self.sync_movie.currentPixmap().scaled(20, 20) if pixmap: point = option.rect.topLeft() painter.drawPixmap(QPoint(point.x(), point.y() + 5), pixmap) option.rect = option.rect.translated(pixmap.width(), 0) super(Delegate, self).paint(painter, option, index)
class SystemTrayIcon(QSystemTrayIcon): def __init__(self, parent): super(SystemTrayIcon, self).__init__() self.parent = parent self.new_folder_window = NewFolderWindow(parent) self.preferences_window = PreferencesWindow() self.setIcon(QIcon(":gridsync.png")) self.right_menu = RightClickMenu(self) self.setContextMenu(self.right_menu) self.activated.connect(self.on_click) self.animation = QMovie() self.animation.setFileName(":sync.gif") self.animation.updated.connect(self.update_animation_frame) self.animation.setCacheMode(True) def update_animation_frame(self): self.setIcon(QIcon(self.animation.currentPixmap())) def set_icon(self, resource): self.setIcon(QIcon(resource)) def on_click(self, value): # pylint: disable=no-self-use if value == QSystemTrayIcon.Trigger: open_gridsync_folder()
class SystemTrayIcon(QSystemTrayIcon): def __init__(self, parent): super(SystemTrayIcon, self).__init__() self.parent = parent self.icon = QIcon(resource(settings['application']['tray_icon'])) self.setIcon(self.icon) self.menu = Menu(self) self.setContextMenu(self.menu) self.activated.connect(self.on_click) self.animation = QMovie() self.animation.setFileName( resource(settings['application']['tray_icon_sync'])) self.animation.updated.connect(self.update) self.animation.setCacheMode(True) def update(self): if self.parent.core.operations: self.animation.setPaused(False) self.setIcon(QIcon(self.animation.currentPixmap())) else: self.animation.setPaused(True) self.setIcon(self.icon) def on_click(self, value): if value == QSystemTrayIcon.Trigger and sys.platform != 'darwin': self.parent.show_main_window()
class Widget_Change_Settings(QWidget): def __init__(self): super().__init__() self.lineedit_testtyp_individual_n_active = False self.lineedit_dgm_delay_uniform_n_active = False self.messagebox_defined_parameters = QMessageBox(self) self.initui() def initui(self): # Window-Title of QWidget 'Widget_Check_CRC' self.windowname = 'Change Settings' self.setWindowTitle("%s" % self.windowname) ################################################################################################################ # QGridLayout 'gridlayout_lv0' ################################################################################################################ self.gridlayout_lv0 = QGridLayout(self) self.setLayout(self.gridlayout_lv0) self.pushbutton = QPushButton("PUSH", self) self.label = QLabel(self) self.movie = QMovie('TestsetCreator/graphics/tenor.gif') self.movie.setCacheMode(QMovie.CacheAll) self.label.setMovie(self.movie) self.gridlayout_lv0.addWidget(self.pushbutton) self.gridlayout_lv0.addWidget(self.label) self.movie.start()
class ImagePlayer(QWidget): def __init__(self, filename, title='', parent=None): QWidget.__init__(self, parent) # Load the file into a QMovie self.movie = QMovie(filename, QByteArray(), self) size = self.movie.scaledSize() self.setGeometry(150, 150, size.width(), size.height()) self.setWindowTitle(title) self.movie_screen = QLabel() # Make label fit the gif self.movie_screen.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred) self.movie_screen.setAlignment(QtCore.Qt.AlignCenter) # Create the layout main_layout = QVBoxLayout() main_layout.addWidget(self.movie_screen) self.setLayout(main_layout) # Add the QMovie object to the label self.movie.setCacheMode(QMovie.CacheAll) self.movie.setSpeed(100) self.movie_screen.setMovie(self.movie) self.movie.start()
class GifPlayer(QWidget): def __init__(self, title, gifFile): super().__init__(self) self.setWindowTitle(title) self.movie = QMovie(gifFile, QByteArray(), self) size = self.movie.scaledSize() self.setGeometry(200, 200, size.width(), size.height()) self.movie_screen = QLabel() self.movie_screen.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) self.movie_screen.setAlignment(Qt.AlignCenter) main_layout = QVBoxLayout() main_layout.addWidget(self.movie_screen) self.setLayout(main_layout) self.movie.setCacheMode(QMovie.CacheAll) self.movie_screen.setMovie(self.movie) self.movie.start() self.movie.loopCount() button = QPushButton('refresh gif', self) button.setToolTip('This is an example button') button.move(10,10) button.clicked.connect(self.on_click) @pyqtSlot() def on_click(self): self.movie = QMovie(gifFile,QByteArray(), self) self.movie_screen.setMovie(self.movie) self.movie.start() print("done")
class SystemTrayIcon(QSystemTrayIcon): def __init__(self, parent): super(SystemTrayIcon, self).__init__() self.parent = parent self.new_folder_window = NewFolderWindow(parent) self.preferences_window = PreferencesWindow() self.setIcon(QIcon(":gridsync.png")) self.right_menu = RightClickMenu(self) self.setContextMenu(self.right_menu) self.activated.connect(self.on_click) self.animation = QMovie() self.animation.setFileName(":sync.gif") self.animation.updated.connect(self.update_animation_frame) self.animation.setCacheMode(True) def update_animation_frame(self): self.setIcon(QIcon(self.animation.currentPixmap())) def set_icon(self, resource): self.setIcon(QIcon(resource)) def on_click(self, value): #self.right_menu.populate() if value == QSystemTrayIcon.Trigger: open_gridsync_folder() def on_quit(self): reactor.stop()
class FunDialogPlayer(QWidget): def __init__(self, parent=None): QWidget.__init__(self, parent) # setGeometry(x_pos, y_pos, width, height) self.setGeometry(200, 200, 400, 400) self.setWindowTitle("QMovie to show animated gif") # set up the movie screen on a label self.movie_screen = QLabel() # expand and center the label self.movie_screen.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) self.movie_screen.setAlignment(Qt.AlignCenter) main_layout = QVBoxLayout() main_layout.addWidget(self.movie_screen) self.setLayout(main_layout) # use an animated gif file you have in the working folder # or give the full file path self.movie = QMovie("giphy.gif", QByteArray(), self) self.movie.setCacheMode(QMovie.CacheAll) self.movie.setSpeed(100) self.movie_screen.setMovie(self.movie) self.movie.start() def start(self): """sart animnation""" self.show() self.movie.start() def stop(self): """stop the animation""" self.movie.stop() self.hide()
class GifPlayer(QWidget): def __init__(self, hsize, vsize, parent=None): super(GifPlayer, self).__init__(parent) # set size and title self.resize(hsize, vsize) self.setWindowTitle('Gif Viewer') # create frame # self.layout = QGridLayout() self.frame = QFrame(self) # self.frame.setLayout(self.layout) # label for movie self.gif_label = QLabel(self.frame) self.gif_label.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) self.gif_label.setAlignment(Qt.AlignCenter) # add stuff to layout # self.layout.addWidget(self.gif_label, 0, 0, 1, 1) # self.layout.setContentsMargins(1, 1, 1, 1) # create actions / shortcuts self.createActions() # Load the file into a QMovie # size = self.movie.scaledSize() # self.setGeometry(200, 200, size.width(), size.height()) # self.setWindowTitle(title) def load_gif(self, fileName): self.gif = QMovie(fileName, QByteArray(), self.gif_label) self.gif.setCacheMode(QMovie.CacheAll) self.gif.setSpeed(100) self.gif_label.setMovie(self.gif) # gif_size = self.gif.scaledSize() # print(gif_size) # self.gif_asp_ratio = # gif_size = self.gif.scaledSize() # self.gif_label.setFixedHeight(gif_size.height()) # self.gif_label.setFixedWidth(gif_size.width()) self.gif.start() # def fix_size(self): # screen_size = self.geometry() # gif_size = self.gif.scaledSize() # print(screen_size) # print(gif_size) def createActions(self): self.close_window_shortcut = QShortcut(QKeySequence("Ctrl+W"), self) self.close_window_shortcut.activated.connect(self.close)
class Ui_MainWindow(object): okno = None def __init__(self): self.tlo = QtWidgets.QLabel( ) # atrapy elementów tak aby nie powstawały błędy self.player = QtWidgets.QLabel() self.enemy = QtWidgets.QLabel() self.score = QtWidgets.QLabel() def setupUi(self, MainWindow): MainWindow.setObjectName("MainWindow") self.centralwidget = QtWidgets.QWidget(MainWindow) self.centralwidget.setCursor(QtGui.QCursor(QtCore.Qt.CrossCursor)) self.centralwidget.setObjectName("centralwidget") self.make_background() self.make_score() self.player = Benek(self.centralwidget) self.centralwidget.close() MainWindow.setCentralWidget(self.centralwidget) self.retranslateUi(MainWindow) QtCore.QMetaObject.connectSlotsByName(MainWindow) def retranslateUi(self, MainWindow): _translate = QtCore.QCoreApplication.translate MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow")) self.score.setText(_translate("MainWindow", "Score: 0")) def make_background(self): self.tlo = QtWidgets.QLabel(self.centralwidget) self.tlo.setGeometry( QtCore.QRect(0, 0, self.okno.width(), self.okno.height())) self.tlo.setText("") self.tlo.setPixmap(QtGui.QPixmap("images/stars_background.gif")) self.tlo.setScaledContents(True) self.tlo.setObjectName("label") self.movie = QMovie("images/stars_background.gif", QByteArray(), self.tlo) self.movie.setCacheMode(QMovie.CacheAll) self.movie.setSpeed(100) self.tlo.setMovie(self.movie) self.movie.start() self.movie.loopCount() def make_score(self): Postac.score = 0 self.score = QtWidgets.QLabel(self.centralwidget) self.score.setGeometry(QtCore.QRect(0, 100, 261, 41)) font = QtGui.QFont() font.setPointSize(24) font.setBold(True) self.score.setFont(font) self.score.setText("Score: 0") self.score.setObjectName("label_4") self.score.setStyleSheet("QLabel#label_4 {color: #aaffff}")
class GifPlayer2(QWidget): def __init__(self, title, gifFile): self.movie = QMovie(gifFile, QByteArray(), self) size = self.movie.scaledSize() self.setGeometry(200, 200, size.width(), size.height()) self.movie.setCacheMode(QMovie.CacheAll) self.movie_screen.setMovie(self.movie) self.movie.start() self.movie.loopCount()
def open(self): self.file = QFileDialog.getOpenFileName(self, "Open File", self.pwd)[0] if self.file == "": return self.information = info.Information(self, self.file) movie = QMovie(self.file, QByteArray(), self) movie.setCacheMode(QMovie.CacheAll) movie.setSpeed(100) self.label.setMovie(movie) movie.start()
class IntroOverlay(_OverlayWidget): opaque_timer = QtCore.QTimer() opaque_timer.setSingleShot(True) finished_signal = QtCore.pyqtSignal() def __init__(self, parent): super(IntroOverlay, self).__init__(parent) self.parent = parent self.intro_mov = QMovie(':/anim/Introduction.gif') self.intro_mov.setCacheMode(QMovie.CacheAll) self.intro_mov.finished.connect(self.finished) self.opaque_timer.timeout.connect(self.set_opaque_for_mouse_events) self.installEventFilter(self) def eventFilter(self, obj, event): if obj is None or event is None: return False if obj is self: if event.type() == QtCore.QEvent.MouseButtonPress: self.mouse_click() return True return False def set_opaque_for_mouse_events(self): self.setAttribute(QtCore.Qt.WA_TransparentForMouseEvents, False) def intro(self): LOGGER.info('Playing introduction in %sx %sy %spx %spx', self.parent.rect().x(), self.parent.rect().y(), self.parent.rect().width(), self.parent.rect().height()) self.movie_screen.setMovie(self.intro_mov) self.movie_screen.setGeometry(self.parent.rect()) self._updateParent() self.opaque_timer.start(1000) self.movie_screen.show() self.show() self.intro_mov.jumpToFrame(0) self.intro_mov.start() def mouse_click(self): self.intro_mov.stop() self.finished() def finished(self): self.movie_screen.hide() self.hide() self.finished_signal.emit()
class ImagePlayer(QWidget): def __init__(self, filename, parent=None): QWidget.__init__(self, parent) self.movie = QMovie(filename) # load the file into a QMovie self.movie_screen = QLabel() self.movie_screen.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) main_layout = QVBoxLayout() main_layout.addWidget(self.movie_screen) self.setLayout(main_layout) self.movie.setCacheMode(QMovie.CacheAll) self.movie.setSpeed(100) self.movie_screen.setMovie(self.movie) self.movie.start()
class SplashScreen(QSplashScreen): def __init__(self, animation, flags, msg=''): QSplashScreen.__init__(self, QPixmap(), flags) self.movie = QMovie(animation) self.movie.setCacheMode(QMovie.CacheAll) self.movie.frameChanged.connect(self.onNextFrame) self.movie.start() self.showMessage(msg, Qt.AlignBottom | Qt.AlignCenter, Qt.white) self.show() @pyqtSlot() def onNextFrame(self): pixmap = self.movie.currentPixmap() self.setPixmap(pixmap) #self.setMask(pixmap.mask())
class GifPlayer(QWidget): def __init__(self, name, parent=None): QWidget.__init__(self, parent) self.movie = QMovie(name, QByteArray(), self) size = self.movie.scaledSize() self.setGeometry(0, 0, size.width(), size.height()) self.im = Image.open(name).size self.movie_screen = QLabel() self.movie_screen.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) self.movie_screen.setAlignment(Qt.AlignCenter) main_layout = QVBoxLayout() main_layout.addWidget(self.movie_screen) self.setLayout(main_layout) self.movie.setCacheMode(QMovie.CacheAll) self.movie_screen.setMovie(self.movie) self.movie.start() self.movie.loopCount() self.btn_s = QPushButton('Scale', self) self.btn_s.resize(80, 25) self.btn_s.move(0, 460) self.btn_s.clicked.connect(self.resizeGIF) self.btn_s.setStyleSheet(""" QPushButton:hover { background-color: red; color: white } QPushButton:!hover { background-color: rgb(105, 105, 105); color: white } QPushButton:pressed { background-color: rgb(205, 92, 92); color: white } """) # Этот метод меняет разрешение гиф-анимации в окне result def resizeGIF(self): try: rect = self.geometry() w = rect.width() h = rect.height() w1, h1 = self.im if w > 20 and h > 20: w -= 20 h -= 20 k = h1 / h w = w1 / k size = QtCore.QSize(int(w), h) movie = self.movie_screen.movie() movie.setScaledSize(size) except Exception as er: print(er)
class Canvas(QWidget): def __init__(self): super().__init__() self.image = QImage() self.movie = QMovie() def play_gif(self, gif_url): self.movie = QMovie(gif_url, QByteArray(), self) self.movie.setCacheMode(QMovie.CacheAll) self.movie.start() self.movie.loopCount() def paintEvent(self, event): qp = QPainter(self) if not self.image.isNull(): image = self.image.scaled(self.size()) qp.drawImage(0, 0, image)
class Main(QMainWindow,FROM_MAIN): def __init__(self,parent=None): super(Main,self).__init__(parent) self.setupUi(self) self.setFixedSize(1920,1080) self.label_7 = QLabel self.setWindowFlags(flags) Dspeak = mainT() self.label_7 = QMovie("./lib/gifloader.gif", QByteArray(), self) self.label_7.setCacheMode(QMovie.CacheAll) self.label_4.setMovie(self.label_7) self.label_7.start() self.ts = time.strftime("%A, %d %B") Dspeak.start() self.label.setPixmap(QPixmap("./lib/tuse.jpg"))
class Loading(QWidget, QMovie): def __init__(self, parent=None): super().__init__() # setGeometry(x_pos, y_pos, width, height) self.setGeometry(200, 200, 400, 400) self.setWindowTitle("QMovie to show animated gif") # set up the movie screen on a label self.movie_screen = QLabel() # expand and center the label self.movie_screen.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) self.movie_screen.setAlignment(Qt.AlignCenter) btn_start = QPushButton("Start Animation") btn_start.clicked.connect(self.start) btn_stop = QPushButton("Stop Animation") btn_stop.clicked.connect(self.stop) main_layout = QVBoxLayout() main_layout.addWidget(self.movie_screen) main_layout.addWidget(btn_start) main_layout.addWidget(btn_stop) self.setLayout(main_layout) # use an animated gif file you have in the working folder # or give the full file path self.movie = QMovie("loading.gif", QByteArray(), self) self.movie.setCacheMode(QMovie.CacheAll) self.movie.setSpeed(100) self.movie_screen.setMovie(self.movie) timer = QTimer(self) self.startAnimation() timer.singleShot(3000, self.stopAnimation) self.show() def start(self): """sart animnation""" self.movie.start() def stop(self): """stop the animation""" self.movie.stop()
class MoviePlayer(QMainWindow): def __init__(self, *args): QMainWindow.__init__(self, *args) # setGeometry(x_pos, y_pos, width, height) self.setGeometry(200, 200, 400, 400) self.setWindowTitle("QMovie to show animated gif") # set up the movie screen on a label self.movie_screen = QLabel() # expand and center the label self.movie_screen.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) #btn_start = QPushButton("Start Animation", self) # btn_start.clicked.connect(self.start) btn_stop = QPushButton("Stop Animation", self) btn_stop.clicked.connect(self.stop) main_layout = QVBoxLayout() main_layout.addWidget(self.movie_screen) # main_layout.addWidget(btn_start) main_layout.addWidget(btn_stop) self.setLayout(main_layout) # use an animated gif file you have in the working folder # or give the full file path self.movie = QMovie("./AG_Dog.gif", QByteArray(), self) self.movie.setCacheMode(QMovie.CacheAll) self.movie.setSpeed(100) self.movie_screen.setMovie(self.movie) self.movie.start() def start(self): """sart animnation""" self.movie.start() def stop(self): """stop the animation""" self.movie.stop() print(self.movie.fileName()) self.movie.start()
class SystemTrayIcon(QSystemTrayIcon): 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) def update(self): if self.gui.core.operations: self.animation.setPaused(False) pixmap = self.animation.currentPixmap() if self.gui.unread_messages: pixmap = BadgedPixmap( pixmap, len(self.gui.unread_messages), 0.6 ) self.setIcon(QIcon(pixmap)) else: self.animation.setPaused(True) if self.gui.unread_messages: self.setIcon(QIcon(BadgedPixmap( self.app_pixmap, len(self.gui.unread_messages), 0.6 ))) else: self.setIcon(self.app_icon) def on_click(self, value): if value == QSystemTrayIcon.Trigger and sys.platform != 'darwin': self.gui.show_main_window()
class Delegate(QStyledItemDelegate): def __init__(self, parent=None): super().__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) def on_frame_changed(self): values = self.parent.model().status_dict.values() if (MagicFolderChecker.LOADING in values or MagicFolderChecker.SYNCING in values or MagicFolderChecker.SCANNING in values): self.parent.viewport().update() else: self.waiting_movie.setPaused(True) self.sync_movie.setPaused(True) def paint(self, painter, option, index): column = index.column() if column == 1: pixmap = None status = index.data(Qt.UserRole) if status == MagicFolderChecker.LOADING: self.waiting_movie.setPaused(False) pixmap = self.waiting_movie.currentPixmap().scaled( 20, 20, Qt.KeepAspectRatio, Qt.SmoothTransformation) elif status in ( MagicFolderChecker.SYNCING, MagicFolderChecker.SCANNING, ): self.sync_movie.setPaused(False) pixmap = self.sync_movie.currentPixmap().scaled( 20, 20, Qt.KeepAspectRatio, Qt.SmoothTransformation) if pixmap: point = option.rect.topLeft() painter.drawPixmap(QPoint(point.x(), point.y() + 5), pixmap) option.rect = option.rect.translated(pixmap.width(), 0) super().paint(painter, option, index)
def show_slides(self): try: i, img_object = self._result.get(True, 5) if isinstance(img_object, QMediaContent): self.MediaPlayer.setMedia(img_object) except Empty: self.timer.stop() return while i != self._next: self._result.put((i, img_object), False) i, img_object = self._result.get() if isinstance(img_object, QMediaContent): self.MediaPlayer.setMedia(img_object) if isinstance(img_object, QMediaContent): # If a movie # self.MediaPlayer.setMedia(img_object) self.layout.setCurrentWidget(self.VideoWidget) self.MediaPlayer.play() elif isinstance(img_object, QMovie): # If a gif size = img_object.scaledSize() img_object = QMovie(img_object.fileName()) img_object.setCacheMode(QMovie.CacheAll) self._gif = img_object img_object.frameChanged.connect(self.gif_frame_changed) self.SlideShowWidget.setMovie(img_object) size.scale(self.SlideShowWidget.size(), Qt.KeepAspectRatio) img_object.setScaledSize(size) img_object.setSpeed(int(self.rate * 100)) self.layout.setCurrentWidget(self.SlideShowWidget) # self.change_playspeed(self.rate) img_object.start() else: # If a picture # print(img_object.size()) self.SlideShowWidget.setPixmap( img_object.scaled(self.SlideShowWidget.size(), Qt.KeepAspectRatio)) self.timer.start(self.delay / self.rate) self.layout.setCurrentWidget(self.SlideShowWidget) self._next += 1 self.threading(self.maxqsize - self._result.qsize())
class Loading(QWidget): def __init__(self): QWidget.__init__(self) self.setup_ui() def setup_ui(self): self.movie = QMovie('assets\\load.gif') gu = ctypes.windll.user32 self.setWindowFlags(Qt.FramelessWindowHint) if int(open('Assets\\scaling.txt', mode='r').read()) == 0: # self.setGeometry(gu.GetSystemMetrics(0) / 2 - 300 / 2, gu.GetSystemMetrics(1) / 2 - 300 / 2, 300, 300) self.setGeometry( QtCore.QRect( gu.GetSystemMetrics(0) / 2 - 300 / 2, gu.GetSystemMetrics(1) / 2 - 300 / 2, 300, 300)) else: self.setGeometry(500, 500, 300, 300) self.lbl = QLabel() self.setStyleSheet("QLabel\n" "{\n" " background-color: #D7CCC8;\n" "}\n") self.lbl.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred) self.lbl.setAlignment(Qt.AlignCenter) main_layout = QVBoxLayout() main_layout.addWidget(self.lbl) self.setLayout(main_layout) self.movie.setCacheMode(QMovie.CacheAll) self.lbl.setMovie(self.movie) self.movie.start() self.movie.loopCount() def start_dialog(self): self.setWindowFlags(Qt.WindowStaysOnTopHint) self.setWindowFlags(Qt.FramelessWindowHint) self.show() def stop_dialog(self): self.hide()
class LoadingScreen(QDialog): def __init__(self, parent, file_path, text): """Initialise the loading screen Arguments: parent {QObject} -- The parent QObject file_path {str} -- Path to file of loading GIF text {str} -- Text to be shown on the loading screen """ super().__init__(parent) self.file = file_path self.text = text self.setWindowFlag(Qt.FramelessWindowHint) self.setFixedSize(200, 200) self.setModal(True) self.init_UI() def init_UI(self): """Initialise the UI by loading the GIF and adding the text label """ vbox = QVBoxLayout() vbox.setAlignment(Qt.AlignHCenter) self.movie_screen = QLabel(self) self.movie_screen.setFixedSize(50, 50) self.movie = QMovie(self.file, QByteArray(), self) self.movie.setScaledSize(self.movie_screen.size()) self.movie.setCacheMode(QMovie.CacheAll) self.movie.setSpeed(100) self.movie_screen.setMovie(self.movie) self.movie.start() self.movie.loopCount() self.loading = QLabel(self.text) self.loading.setAlignment(Qt.AlignCenter) vbox.addStretch(2) vbox.addWidget(self.movie_screen, Qt.AlignCenter) vbox.addSpacing(10) vbox.addWidget(self.loading, Qt.AlignHCenter) vbox.addStretch(1) self.setLayout(vbox)
class Load(QWidget): def __init__(self): super().__init__() self.movie = QMovie("load.gif", QByteArray(), self) size = self.size() screenGeometry = QDesktopWidget().screenGeometry(-1).size() self.setGeometry((screenGeometry.width() - size.width()) // 2, (screenGeometry.height() - size.height()) // 2, size.width(), size.height()) self.setWindowTitle('') self.movie_screen = QLabel() self.movie_screen.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) self.movie_screen.setAlignment(Qt.AlignCenter) main_layout = QVBoxLayout() main_layout.addWidget(self.movie_screen) self.setLayout(main_layout) self.movie.setCacheMode(QMovie.CacheAll) self.movie_screen.setMovie(self.movie) self.frame_count = self.movie.frameCount() self.movie.frameChanged.connect(self.frameChanged) self.frame = 0 self.setWindowFlags(Qt.FramelessWindowHint) self.setAttribute(Qt.WA_NoSystemBackground, True) self.setAttribute(Qt.WA_TranslucentBackground, True) self.movie.start() self.app = MainApp() self.movie.loopCount() def frameChanged(self): self.frame += 1 if self.frame >= self.frame_count: self.movie.stop() self.movie.setParent(None) self.movie.deleteLater() self.setAttribute(Qt.WA_NoSystemBackground, False) self.setAttribute(Qt.WA_TranslucentBackground, False) self.destroy() self.app.show()
def generate_gif(self): img: Image imgs: List[Image] # https://pillow.readthedocs.io/en/stable/handbook/image-file-formats.html#gif select_frames_labels = self.layout_children(self.select_frames_layout) if not select_frames_labels: self.adjust_corgo() return pixmaps = [ i.original_pixmap for i in select_frames_labels if i.highlighted ] height = int(self.height.text()) img, *imgs = [ qpixmap_to_pil(i.scaledToHeight(height)) for i in pixmaps ] delay = int(self.delay.text()) bytesio = io.BytesIO() img.save(fp=bytesio, format='GIF', append_images=imgs, save_all=True, duration=delay, loop=0) self.gif_qbytearray = QByteArray(bytesio.getvalue()) bytesio.close() self.gif_qbuffer = QBuffer(self.gif_qbytearray) gif = QMovie() gif.setDevice(self.gif_qbuffer) gif.setCacheMode(QMovie.CacheAll) print(f'Movie isValid() {gif.isValid()}') self.gif_view.setMovie(gif) gif.start()
class Main(QMainWindow, FROM_MAIN): def __init__(self, parent=None): super(Main, self).__init__(parent) self.setupUi(self) self.setFixedSize(1920, 1080) self.label_7 = QLabel self.exitB.setStyleSheet( "background-image:url(./lib/exit - Copy.png);\n" "border:none;") self.exitB.clicked.connect(self.close) self.setWindowFlags(flags) Dspeak = mainT() self.label_7 = QMovie("./lib/gifloader.gif", QByteArray(), self) self.label_7.setCacheMode(QMovie.CacheAll) self.label_4.setMovie(self.label_7) self.label_7.start() self.ts = time.strftime("%A, %d %B") Dspeak.start() self.label.setPixmap(QPixmap("./lib/tuse.jpg")) self.label_5.setText("<font size=8 color='white'>" + self.ts + "</font>") self.label_5.setFont(QFont(QFont('Acens', 8)))
class OCCMovie(dispocc): def __init__(self, disp=True, touch=True): super().__init__(disp=disp, touch=touch) self.MovieMenu() def MovieMenu(self): self.add_menu("Movie") self.add_function("Movie", self.export_cap) self.add_function("Movie", self.movie_start) self.add_function("Movie", self.movie_stop) def movie_start(self): """sart animnation""" # use an animated gif file you have in the working folder # or give the full file path self.movie = QMovie(self.tempname + ".gif", QByteArray(), self.wi) self.movie.setCacheMode(QMovie.CacheAll) self.movie.setSpeed(100) # self.movie_screen.setMovie(self.movie) self.movie.start() def movie_stop(self): """stop the animation""" self.movie.stop()
class ImageViewer(QMainWindow): def __init__(self): super(ImageViewer, self).__init__() self.printer = QPrinter() self.scaleFactor = 0.0 self.imageLabel = QLabel() self.imageLabel.setBackgroundRole(QPalette.Base) self.imageLabel.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Ignored) self.imageLabel.setScaledContents(True) self.imageLabel.setAlignment(Qt.AlignCenter) self.scrollArea = QScrollArea() self.scrollArea.setBackgroundRole(QPalette.Dark) self.scrollArea.setWidget(self.imageLabel) self.setCentralWidget(self.scrollArea) self.scrollArea.setAlignment(Qt.AlignCenter) self.createActions() self.createMenus() self.setWindowTitle("Image Viewer") self.resize(500, 400) self.setWindowIcon(QIcon('./res/Sketch-Icon.png')) def open(self): # 打开图片后根据weight重新调整大小 fileName, _ = QFileDialog.getOpenFileName(self, "Open File", QDir.currentPath()) if fileName: # 如果是webp格式用PIL # 如果是psd用PSDtool # gif格式? fileType = fileName.split('.')[-1] if fileType == 'gif': #QMessageBox.information(self, "file type", "type:%s"%(fileType)) self.movie = QMovie(fileName) self.movie.setCacheMode(QMovie.CacheAll) self.movie.setSpeed(100) self.imageLabel.setMovie(self.movie) self.movie.start() if not self.fitToWindowAct.isChecked(): self.imageLabel.adjustSize() elif fileType == 'psd': img = PSDImage.load(fileName) img = img.as_PIL() img.save('./res/temp.jpg') image = QImage('./res/temp.jpg') if image.isNull(): QMessageBox.information(self, "Image Viewer", "Cannot load %s." % (fileName)) return self.imageLabel.setPixmap(QPixmap.fromImage(image)) self.scaleFactor = 1.0 self.printAct.setEnabled(True) self.fitToWindowAct.setEnabled(True) self.updateActions() if not self.fitToWindowAct.isChecked(): self.imageLabel.adjustSize() elif fileType == 'svg': svg = QtSvg.QSvgRenderer(fileName) img = QImage(svg.defaultSize().width(), svg.defaultSize().height(), QImage.Format_ARGB32) p = QPainter(img) svg.render(p) img.save('./res/temp.png') p.end() image = QImage('./res/temp.png') if image.isNull(): QMessageBox.information(self, "Image Viewer", "Cannot load %s." % (fileName)) return self.imageLabel.setPixmap(QPixmap.fromImage(image)) self.scaleFactor = 1.0 self.printAct.setEnabled(True) self.fitToWindowAct.setEnabled(True) self.updateActions() if not self.fitToWindowAct.isChecked(): self.imageLabel.adjustSize() else: image = QImage(fileName) if image.isNull(): QMessageBox.information(self, "Image Viewer", "Cannot load %s." % (fileName)) return self.imageLabel.setPixmap(QPixmap.fromImage(image)) self.scaleFactor = 1.0 self.printAct.setEnabled(True) self.fitToWindowAct.setEnabled(True) self.updateActions() if not self.fitToWindowAct.isChecked(): self.imageLabel.adjustSize() def print_(self): dialog = QPrintDialog(self.printer, self) if dialog.exec_(): painter = QPainter(self.printer) rect = painter.viewport() size = self.imageLabel.pixmap().size() size.scale(rect.size(), Qt.KeepAspectRatio) painter.setViewport(rect.x(), rect.y(), size.width(), size.height()) painter.setWindow(self.imageLabel.pixmap().rect()) painter.drawPixmap(0, 0, self.imageLabel.pixmap()) def zoomIn(self): self.scaleImage(1.25) def zoomOut(self): self.scaleImage(0.8) def normalSize(self): self.imageLabel.adjustSize() self.scaleFactor = 1.0 def fitToWindow(self): fitToWindow = self.fitToWindowAct.isChecked() self.scrollArea.setWidgetResizable(fitToWindow) if not fitToWindow: self.normalSize() self.updateActions() def about(self): QMessageBox.about(self, "About Image Viewer", "<p>The <b>Image Viewer</b> example shows how to combine " "QLabel and QScrollArea to display an image. QLabel is " "typically used for displaying text, but it can also display " "an image. QScrollArea provides a scrolling view around " "another widget. If the child widget exceeds the size of the " "frame, QScrollArea automatically provides scroll bars.</p>" "<p>The example demonstrates how QLabel's ability to scale " "its contents (QLabel.scaledContents), and QScrollArea's " "ability to automatically resize its contents " "(QScrollArea.widgetResizable), can be used to implement " "zooming and scaling features.</p>" "<p>In addition the example shows how to use QPainter to " "print an image.</p>") def rgbColor(self): pass def hexColor(self): pass def createActions(self): self.openAct = QAction("&Open...", self, shortcut="Ctrl+O", triggered=self.open) self.printAct = QAction("&Print...", self, shortcut="Ctrl+P", enabled=False, triggered=self.print_) self.exitAct = QAction("E&xit", self, shortcut="Ctrl+Q", triggered=self.close) self.zoomInAct = QAction("Zoom &In (25%)", self, shortcut="Ctrl++", enabled=False, triggered=self.zoomIn) self.zoomOutAct = QAction("Zoom &Out (25%)", self, shortcut="Ctrl+-", enabled=False, triggered=self.zoomOut) self.normalSizeAct = QAction("&Normal Size", self, shortcut="Ctrl+S", enabled=False, triggered=self.normalSize) self.fitToWindowAct = QAction("&Fit to Window", self, enabled=False, checkable=True, shortcut="Ctrl+F", triggered=self.fitToWindow) self.rgbColor = QAction("&RGB Color", self, enabled=False, checkable=True, triggered=self.rgbColor) self.hexColor = QAction("&HEX Color", self, enabled=False, checkable=True, triggered=self.hexColor) self.aboutAct = QAction("&About", self, triggered=self.about) self.aboutQtAct = QAction("About &Qt", self, triggered=QApplication.instance().aboutQt) def createMenus(self): self.fileMenu = QMenu("&File", self) self.fileMenu.addAction(self.openAct) self.fileMenu.addAction(self.printAct) self.fileMenu.addSeparator() self.fileMenu.addAction(self.exitAct) self.viewMenu = QMenu("&View", self) self.viewMenu.addAction(self.zoomInAct) self.viewMenu.addAction(self.zoomOutAct) self.viewMenu.addAction(self.normalSizeAct) self.viewMenu.addSeparator() self.viewMenu.addAction(self.fitToWindowAct) self.pickColor = QMenu("&PickColor", self) self.pickColor.addAction(self.rgbColor) self.pickColor.addAction(self.hexColor) self.helpMenu = QMenu("&Help", self) self.helpMenu.addAction(self.aboutAct) self.helpMenu.addAction(self.aboutQtAct) self.menuBar().addMenu(self.fileMenu) self.menuBar().addMenu(self.viewMenu) self.menuBar().addMenu(self.pickColor) self.menuBar().addMenu(self.helpMenu) def updateActions(self): self.zoomInAct.setEnabled(not self.fitToWindowAct.isChecked()) self.zoomOutAct.setEnabled(not self.fitToWindowAct.isChecked()) self.normalSizeAct.setEnabled(not self.fitToWindowAct.isChecked()) def scaleImage(self, factor): self.scaleFactor *= factor self.imageLabel.resize(self.scaleFactor * self.imageLabel.pixmap().size()) self.adjustScrollBar(self.scrollArea.horizontalScrollBar(), factor) self.adjustScrollBar(self.scrollArea.verticalScrollBar(), factor) self.zoomInAct.setEnabled(self.scaleFactor < 3.0) self.zoomOutAct.setEnabled(self.scaleFactor > 0.333) def adjustScrollBar(self, scrollBar, factor): scrollBar.setValue(int(factor * scrollBar.value() + ((factor - 1) * scrollBar.pageStep()/2)))
class MoviePlayer(QWidget): def __init__(self, parent=None): super(MoviePlayer, self).__init__(parent) self.movie = QMovie(self) self.movie.setCacheMode(QMovie.CacheAll) self.movieLabel = QLabel("No movie loaded") self.movieLabel.setAlignment(Qt.AlignCenter) self.movieLabel.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Ignored) self.movieLabel.setBackgroundRole(QPalette.Dark) self.movieLabel.setAutoFillBackground(True) self.currentMovieDirectory = '' self.createControls() self.createButtons() self.movie.frameChanged.connect(self.updateFrameSlider) self.movie.stateChanged.connect(self.updateButtons) self.fitCheckBox.clicked.connect(self.fitToWindow) self.frameSlider.valueChanged.connect(self.goToFrame) self.speedSpinBox.valueChanged.connect(self.movie.setSpeed) mainLayout = QVBoxLayout() mainLayout.addWidget(self.movieLabel) mainLayout.addLayout(self.controlsLayout) mainLayout.addLayout(self.buttonsLayout) self.setLayout(mainLayout) self.updateFrameSlider() self.updateButtons() self.setWindowTitle("Movie Player") self.resize(400, 400) def open(self): fileName, _ = QFileDialog.getOpenFileName(self, "Open a Movie", self.currentMovieDirectory) if fileName: self.openFile(fileName) def openFile(self, fileName): self.currentMovieDirectory = QFileInfo(fileName).path() self.movie.stop() self.movieLabel.setMovie(self.movie) self.movie.setFileName(fileName) self.movie.start() self.updateFrameSlider(); self.updateButtons(); def goToFrame(self, frame): self.movie.jumpToFrame(frame) def fitToWindow(self): self.movieLabel.setScaledContents(self.fitCheckBox.isChecked()) def updateFrameSlider(self): hasFrames = (self.movie.currentFrameNumber() >= 0) if hasFrames: if self.movie.frameCount() > 0: self.frameSlider.setMaximum(self.movie.frameCount() - 1) elif self.movie.currentFrameNumber() > self.frameSlider.maximum(): self.frameSlider.setMaximum(self.movie.currentFrameNumber()) self.frameSlider.setValue(self.movie.currentFrameNumber()) else: self.frameSlider.setMaximum(0) self.frameLabel.setEnabled(hasFrames) self.frameSlider.setEnabled(hasFrames) def updateButtons(self): state = self.movie.state() self.playButton.setEnabled(self.movie.isValid() and self.movie.frameCount() != 1 and state == QMovie.NotRunning) self.pauseButton.setEnabled(state != QMovie.NotRunning) self.pauseButton.setChecked(state == QMovie.Paused) self.stopButton.setEnabled(state != QMovie.NotRunning) def createControls(self): self.fitCheckBox = QCheckBox("Fit to Window") self.frameLabel = QLabel("Current frame:") self.frameSlider = QSlider(Qt.Horizontal) self.frameSlider.setTickPosition(QSlider.TicksBelow) self.frameSlider.setTickInterval(10) speedLabel = QLabel("Speed:") self.speedSpinBox = QSpinBox() self.speedSpinBox.setRange(1, 9999) self.speedSpinBox.setValue(100) self.speedSpinBox.setSuffix("%") self.controlsLayout = QGridLayout() self.controlsLayout.addWidget(self.fitCheckBox, 0, 0, 1, 2) self.controlsLayout.addWidget(self.frameLabel, 1, 0) self.controlsLayout.addWidget(self.frameSlider, 1, 1, 1, 2) self.controlsLayout.addWidget(speedLabel, 2, 0) self.controlsLayout.addWidget(self.speedSpinBox, 2, 1) def createButtons(self): iconSize = QSize(36, 36) openButton = QToolButton() openButton.setIcon(self.style().standardIcon(QStyle.SP_DialogOpenButton)) openButton.setIconSize(iconSize) openButton.setToolTip("Open File") openButton.clicked.connect(self.open) self.playButton = QToolButton() self.playButton.setIcon(self.style().standardIcon(QStyle.SP_MediaPlay)) self.playButton.setIconSize(iconSize) self.playButton.setToolTip("Play") self.playButton.clicked.connect(self.movie.start) self.pauseButton = QToolButton() self.pauseButton.setCheckable(True) self.pauseButton.setIcon(self.style().standardIcon(QStyle.SP_MediaPause)) self.pauseButton.setIconSize(iconSize) self.pauseButton.setToolTip("Pause") self.pauseButton.clicked.connect(self.movie.setPaused) self.stopButton = QToolButton() self.stopButton.setIcon(self.style().standardIcon(QStyle.SP_MediaStop)) self.stopButton.setIconSize(iconSize) self.stopButton.setToolTip("Stop") self.stopButton.clicked.connect(self.movie.stop) quitButton = QToolButton() quitButton.setIcon(self.style().standardIcon(QStyle.SP_DialogCloseButton)) quitButton.setIconSize(iconSize) quitButton.setToolTip("Quit") quitButton.clicked.connect(self.close) self.buttonsLayout = QHBoxLayout() self.buttonsLayout.addStretch() self.buttonsLayout.addWidget(openButton) self.buttonsLayout.addWidget(self.playButton) self.buttonsLayout.addWidget(self.pauseButton) self.buttonsLayout.addWidget(self.stopButton) self.buttonsLayout.addWidget(quitButton) self.buttonsLayout.addStretch()
class ImagePlayer(QWidget): """Gif player""" def __init__(self, parent=None): """Initialisation of GUI""" QWidget.__init__(self, parent) self.close_with_dialog = True self.i_ip = 0 self.filename = QFileDialog.getOpenFileName(self, 'Open file', '.')[0] if not self.filename: sys.exit() path = os.path.dirname(self.filename) ldir = os.listdir(path=path) os.chdir(path) self.pall_widget = QWidget() self.frames_widget = QWidget() self.files = [ os.path.abspath(i) for i in ldir if os.path.isfile(i) and GifInfo.try_parse(i) ] if not self.files: raise ValueError("There is no correct images") if self.filename not in self.files: descr = "Corrupt image" inform = "Automatic select next image in directory..." QMessageBox.about(self, descr, inform) self.filename = self.files[0] self.gifinfos = {self.filename: GifInfo(self.filename)} self.gifinfo = self.gifinfos[self.filename] self.f_ip = self.files.index(self.filename) self.played = True self.init_buttons() self.init_qmovie() self.init_main_layout() self.setWindowTitle("Gif Parse") self.tmp_widget = QWidget() self.setLayout(self.main_layout) def on_start(self): """Start playing""" if self.played: self.play_b.text = "Play" self.movie.stop() else: self.play_b.text = "Stop" self.movie.start() self.played = not self.played def init_qmovie(self): """QMovie Initialisation""" self.movie = QMovie(self.filename, QByteArray(), self) self.movie_screen = QLabel() self.movie_screen.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) self.movie.setCacheMode(QMovie.CacheAll) self.movie.setSpeed(100) self.movie_screen.setMovie(self.movie) self.movie.start() def init_buttons(self): """Buttons Initialisation""" self.play_b = QPushButton("&Play") self.play_b.clicked.connect(self.on_start) self.nxt_b = QPushButton(">") self.nxt_b.clicked.connect(self.next_gif_b) self.prv_b = QPushButton("<") self.prv_b.clicked.connect(self.prev_gif_b) self.info_b = QPushButton("&Info") self.info_b.clicked.connect(self.on_info) self.readme_b = QPushButton("&Readme") self.readme_b.clicked.connect(self.on_readme) def init_main_layout(self): """Initialization of main layout""" self.main_layout = QGridLayout() self.main_layout.setSpacing(2) self.main_layout.addWidget(self.movie_screen, 0, 0, 1, 5) self.main_layout.addWidget(self.play_b, 1, 1) self.main_layout.addWidget(self.prv_b, 1, 0) self.main_layout.addWidget(self.nxt_b, 1, 2) self.main_layout.addWidget(self.info_b, 1, 3) self.main_layout.addWidget(self.readme_b, 1, 4) def on_info(self): """Show info""" info = self.gifinfo infos = [] infos.append(info.spec) infos.append(str(info.size[0]) + "x" + str(info.size[1])) infos.append(str(info.aratio)) infos.append(str(info.loops)) infos.append(str(len(info.frames))) fields_name = [ "Type", "Size", "Ratio", "Count of loops", "Count of frames" ] self.tmp_widget.setLayout(self.layout()) layout = QGridLayout(self) layout.setSpacing(8) back = QPushButton("Back") back.clicked.connect(self.on_back) full = QPushButton("Full info to txt") full.clicked.connect(self.on_make_info) for text, i in zip(infos, range(len(infos))): widget = QLineEdit(text) widget.setReadOnly(True) layout.addWidget(QLabel(fields_name[i]), i, 0) layout.addWidget(widget, i, 1, 1, 1) if info.comments: widget = QLineEdit(info.comments[0]) widget.setReadOnly(True) layout.addWidget(QLabel("Comments:"), 6, 0) layout.addWidget(widget, 6, 1) pal_b = QPushButton("Pallete") pal_b.clicked.connect(self.on_pallete_b) fr_b = QPushButton("About frames") fr_b.clicked.connect(self.on_frames_b) layout.addWidget(pal_b, 7, 0) layout.addWidget(fr_b, 7, 1) layout.addWidget(full, 8, 0) layout.addWidget(back, 8, 1) self.setLayout(layout) def on_readme(self): """Show readme""" self.tmp_widget.setLayout(self.layout()) layout = QGridLayout(self) layout.setSpacing(6) back = QPushButton("Back") back.clicked.connect(self.on_back) with open(DIR + '/readme.txt', mode='r') as txt: from_file = txt.read() txt_widget = QTextEdit() for line in from_file.split('\n'): txt_widget.append(line) txt_widget.setReadOnly(True) layout.addWidget(txt_widget, 0, 0, 1, 5) layout.addWidget(back, 5, 1) self.setLayout(layout) def on_back(self): """Back to main_layout""" QWidget().setLayout(self.layout()) self.setLayout(self.tmp_widget.layout()) def on_back_pal(self): """Back to main_layout""" QWidget().setLayout(self.layout()) self.setLayout(self.pall_widget.layout()) def on_back_frames(self): """Back to main_layout""" QWidget().setLayout(self.layout()) self.setLayout(self.frames_widget.layout()) def on_make_info(self): """Make info file""" name = str(os.path.basename(self.gifinfo.name)).split('.')[0] if not os.path.exists(name + "info.txt"): with open(name + "info.txt", mode='w') as file: file.write(self.gifinfo.to_str()) QMessageBox.about(self, "Make txt", "Finished") def closeEvent(self, event): """When window closed""" quit_msg = "Are you sure you want to close this program?" if self.close_with_dialog: reply = QMessageBox.question(self, 'Message', quit_msg, QMessageBox.Yes, QMessageBox.No) else: reply = QMessageBox.Yes if reply == QMessageBox.Yes: event.accept() else: event.ignore() def contextMenuEvent(self, event): """Handling context Menu""" menu = QMenu(self) open_act = menu.addAction("Open new") menu.addAction("Quit") action = menu.exec_(self.mapToGlobal(event.pos())) self.close_with_dialog = False self.close() if action == open_act: main() def next_gif(self, direction): """Choose next gif in directory""" self.f_ip += direction self.f_ip += len(self.files) self.f_ip %= len(self.files) self.i_ip = 0 self.filename = self.files[self.f_ip] if self.filename not in self.gifinfos: self.gifinfos[self.filename] = GifInfo(self.filename) self.gifinfo = self.gifinfos[self.filename] self.movie = QMovie(self.filename, QByteArray(), self) self.movie_screen.setMovie(self.movie) self.movie.start() def next_gif_b(self): """nxt_b event""" self.next_gif(1) def prev_gif_b(self): """prv_b event""" self.next_gif(-1) def keyPressEvent(self, event): """Key pressed event""" if event.key() == 44: self.next_gif(-1) elif event.key() == 46: self.next_gif(1) def on_pallete_b(self): """Make layout for pallete window""" lay = QGridLayout() wind = QWidget() wind_lay = QGridLayout() wind.setLayout(lay) self.pall_widget.setLayout(self.layout()) for i, color in enumerate(self.gifinfo.colors): lab = QLabel() col = QColor(*color) lab.setStyleSheet("QFrame { background-color: %s }" % col.name()) lay.addWidget(lab, i // 10, i % 10) back = QPushButton("Back") scroll = QScrollArea() scroll.setWidget(wind) scroll.setWidgetResizable(True) scroll.setFixedHeight(200) wind_lay.addWidget(scroll) wind_lay.addWidget(back) self.setLayout(wind_lay) back.clicked.connect(self.on_back_pal) @staticmethod def make_frame_wid(frame): """Make specific widget for some gif's frame""" lay = QGridLayout() wid = QWidget() colors = QWidget() colors_lay = QGridLayout() colors.setLayout(colors_lay) data = [] data += (frame.x, frame.y) data += (frame.width, frame.height) data.append(frame.delay) names = ["x", "y", "Width", "Heigth", "Delay"] for i in range(len(data)): lay.addWidget(QLabel(names[i]), i, 0) widget = QLineEdit(str(data[i])) widget.setReadOnly(True) lay.addWidget(widget, i, 1) for i, color in enumerate(frame.colors): lab = QLabel() col = QColor(*color) lab.setStyleSheet("QFrame { background-color: %s }" % col.name()) colors_lay.addWidget(lab, 5 + i // 10, i % 10) scroll = QScrollArea() scroll.setWidget(colors) scroll.setWidgetResizable(True) scroll.setFixedHeight(200) lay.addWidget(scroll, 4, 0, 2, 2) wid.setLayout(lay) return wid def change_frame_lay(self, lay): """Select info about selected frame in ComboBox""" self.lays[self.prev].setLayout(self.fr_wid.layout()) self.prev = lay self.fr_wid.setLayout(self.lays[lay].layout()) def on_frames_b(self): """Frames info event""" empty_lay = QGridLayout() self.frames_widget.setLayout(self.layout()) self.lays = {} self.prev = '0' self.fr_wid = QWidget() lay = QGridLayout() for i, frame in enumerate(self.gifinfo.frames): self.lays[str(i)] = ImagePlayer.make_frame_wid(frame) combs = QComboBox() combs.addItems([str(i) for i in range(len(self.gifinfo.frames))]) combs.activated[str].connect(self.change_frame_lay) lay.addWidget(combs) if self.lays: self.fr_wid.setLayout(self.lays['0'].layout()) else: self.fr_wid.setLayout(empty_lay) lay.addWidget(self.fr_wid) back = QPushButton("Back") lay.addWidget(back) back.clicked.connect(self.on_back_frames) self.setLayout(lay)
class Pomodoro(): def __init__(self): self.timer = 0 self.progress_value = 0 self.running = False self.cycles = 0 self.state = STATE.WORK self.beep = AudioSegment.from_mp3("pomodoro.mp3") def swap_state(self): if self.state == STATE.WORK: self.state = STATE.PAUSE else: self.state = STATE.WORK self.cycles += 1 self.set_cycles() def swap(self): self.swap_state() self.state_label.setText(STATE_LABELS[self.state]) self.timer = 0 play(self.beep) def reset(self): self.timer = 0 self.change_progress_bar() self.change_time_label() def toggle(self): if self.running: self.toggle_button.setText('Play') self.running = False self.loop_stopper.set() self.movie.stop() else: self.toggle_button.setText('Pause') self.running = True self.run() self.movie.start() def set_cycles(self): self.cycles_label.setText('{} cycles'.format(self.cycles)) def run(self): self.loop_stopper = threading.Event() self.window.loop_stopper = self.loop_stopper self.loop = threading.Thread(target=self.clock_loop, args=(self.loop_stopper, )) self.loop.start() def change_progress_bar(self): new_progress_value = int(self.timer / CYCLE_LENGTHS[self.state] * 100) if new_progress_value != self.progress_value: self.progress_value = new_progress_value self.progress.setValue(self.progress_value) def change_time_label(self): mins = self.timer // 60 secs = self.timer - mins * 60 total_mins = CYCLE_LENGTHS[self.state] // 60 total_secs = CYCLE_LENGTHS[self.state] - total_mins * 60 new_time_label = "{:02d}:{:02d} / {:02d}:{:02d}".format( mins, secs, total_mins, total_secs) self.time_label.setText(new_time_label) def clock_loop(self, stopper): while not stopper.isSet(): self.timer += 1 self.change_progress_bar() self.change_time_label() if self.timer == CYCLE_LENGTHS[self.state]: self.swap() time.sleep(1) def exec(self): self.app = QApplication([]) # button font button_font = QtGui.QFont("Sans", 13, QtGui.QFont.Bold) # toggle button self.toggle_button = QPushButton('Start') self.toggle_button.setCheckable(True) self.toggle_button.clicked.connect(self.toggle) self.toggle_button.setFont(button_font) # reset button self.reset_button = QPushButton('Reset') self.reset_button.clicked.connect(self.reset) self.reset_button.setFont(button_font) # progress label self.progress_label = QLabel() self.movie = QMovie("spinner.gif") self.progress_label.setMovie(self.movie) self.progress_label.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) self.progress_label.setAlignment(Qt.AlignCenter) # label self.label = QLabel('Pomodoro timer') self.pixmap = QPixmap('pomodoro.png') self.label.setPixmap(self.pixmap) # time label self.time_label = QLabel('00:00 / 25:00') self.time_label.setFont(button_font) # cycles label self.cycles_label = QLabel('0 cycles') cycles_font = QtGui.QFont("Sans", 12, QtGui.QFont.Bold) self.cycles_label.setFont(cycles_font) # state label state_font = QtGui.QFont("Sans", 18, QtGui.QFont.Bold) self.state_label = QLabel(STATE_LABELS[self.state]) self.state_label.setFont(state_font) # progressbar self.progress = QProgressBar() self.progress.setMaximum(100) self.progress.setMinimum(0) self.progress.setValue(0) self.window = CloseableQWidget(self) self.window.setGeometry(770, 440, 400, 200) self.outer_vertical = QVBoxLayout() self.inner_horizonal = QHBoxLayout() self.buttons_vertical = QVBoxLayout() self.slider_clock_layout = QHBoxLayout() self.labels = QHBoxLayout() self.outer_vertical.addLayout(self.inner_horizonal) self.inner_horizonal.addWidget(self.label) self.inner_horizonal.addLayout(self.buttons_vertical) self.buttons_vertical.addWidget(self.toggle_button) self.buttons_vertical.addWidget(self.reset_button) self.slider_clock_layout.addWidget(self.progress) self.slider_clock_layout.addWidget(self.time_label) self.labels.addWidget(self.state_label) self.labels.addWidget(self.cycles_label) self.labels.addWidget(self.progress_label, alignment=Qt.AlignRight) self.outer_vertical.addLayout(self.labels) self.outer_vertical.addLayout(self.slider_clock_layout) self.window.setLayout(self.outer_vertical) self.window.show() # gif options self.movie.setCacheMode(QMovie.CacheAll) self.progress_label.setMovie(self.movie) self.movie.jumpToFrame(1) self.movie.loopCount() self.app.setStyle('Fusion') sys.exit(self.app.exec_())
class alarmChecker(QWidget): def __init__(self, parent): super(alarmChecker, self).__init__() self.parent = parent self.networkError = False self.loadAlarm() self.getAlarm() self.getTimeout() self.getTimer() self.setLayout(self.alarm_layout) def loadAlarm(self): self.list_alarm = [] config = ConfigParser.ConfigParser() config.readfp(open(self.parent.config_path + 'alarm.cfg')) for a in config.sections(): dict = {"tableName": a} for b in config.options(a): dict[b] = config.get(a, b) self.list_alarm.append(dict) def getAlarm(self): self.alarm_layout = QGridLayout() self.movie = QMovie(self.parent.os_path + "/img/giphy2.gif", QByteArray(), self) self.movie_screen = QLabel() # Make label fit the gif self.movie_screen.setFixedSize(80, 50) # Add the QMovie object to the label self.movie.setCacheMode(QMovie.CacheAll) self.movie.setSpeed(100) self.movie_screen.setMovie(self.movie) self.movie.start() self.timeout_ack = [] self.dialog = self.dialogTimeout() self.dialog.hide() self.label_acq = QPushButton("ACQUISITION") self.label_acq.clicked.connect(self.dialog.show) self.label_acq.setFixedHeight(50) self.setColor("QPushButton", self.label_acq, "green") self.alarm_layout.addWidget(self.movie_screen, 0, 0, 1, 1) self.alarm_layout.addWidget(self.label_acq, 0, 1, 1, 2) for i, device in enumerate(self.list_alarm): name = device["tableName"] + device["key"] button = QPushButton(device["label"].upper()) button.setFixedHeight(50) self.setColor("QPushButton", button, "green") button.clicked.connect(partial(self.showWarning, "msg_%s" % name)) self.alarm_layout.addWidget(button, 0, i + 3, 1, 1) setattr(self, "alarm_%s" % name, button) self.watcher_alarm = QTimer(self) self.watcher_alarm.setInterval(5000) self.watcher_alarm.timeout.connect(self.checkCriticalValue) self.watcher_alarm.start() def getTimeout(self): self.device_dict = copy.deepcopy(self.parent.device_dict) self.timeout_limit = 90 self.list_timeout = [key for key, value in self.parent.device_dict.iteritems()] self.last_date = {} self.last_time = {} for key, value in self.device_dict.iteritems(): self.last_date[key] = 0 self.last_time[key] = datetime.datetime.now() def getTimer(self): watcher_timeout = QTimer(self) watcher_timeout.singleShot(2000, partial(self.showTimeout, 0)) self.checker_timeout = QTimer(self) self.checker_timeout.setInterval(15000) self.checker_timeout.timeout.connect(self.checkTimeout) self.checker_timeout.start() def showTimeout(self, i): for timeout in self.timeout_ack: try: self.list_timeout.remove(timeout) except ValueError: pass if not self.networkError: if self.list_timeout: if i < len(self.list_timeout): self.label_acq.setText("TIME OUT ON %s" % self.list_timeout[i]) self.setColor("QPushButton", self.label_acq, "red") i += 1 else: i = 0 else: self.label_acq.setText("ACQUISITION") self.setColor("QPushButton", self.label_acq, "green") else: self.label_acq.setText("SERVER LOST") self.setColor("QPushButton", self.label_acq, "orange") watcher_timeout = QTimer(self) watcher_timeout.singleShot(2000, partial(self.showTimeout, i)) def checkTimeout(self): for key, value in self.device_dict.iteritems(): return_values = self.parent.db.getLastData(key, "id") if return_values == -5: self.networkError = True elif type(return_values) is int: self.parent.showError(return_values) else: date, id = return_values self.networkError = False if date != self.last_date[key]: if self.last_date[key] != 0: if key in self.list_timeout: self.list_timeout.remove(key) self.last_time[key] = datetime.datetime.now() self.last_date[key] = date else: if (datetime.datetime.now() - self.last_time[key]).total_seconds() > self.timeout_limit: if key not in self.list_timeout: self.list_timeout.append(key) def checkCriticalValue(self): for device in self.list_alarm: name = device["tableName"] + device["key"] return_values = self.parent.db.getLastData(device["tableName"], device["key"]) if type(return_values) is not int: date, [val] = return_values fmt = "{:.5e}" if len(str(val)) > 8 else "{:.2f}" if float(device["lower_bound"]) <= val < float(device["higher_bound"]): msg = "%s OK \r %s <= %s < %s" % ( device["label"], device["lower_bound"], fmt.format(val), device["higher_bound"]) self.setColor("QPushButton", getattr(self, "alarm_%s" % name), "green") else: msg = "WARNING ! %s OUT OF RANGE \r %s <= %s < %s" % ( device["label"], device["lower_bound"], fmt.format(val), device["higher_bound"]) self.setColor("QPushButton", getattr(self, "alarm_%s" % name), "red") setattr(self, "msg_%s" % name, msg) else: print "code error : %i" % val def setColor(self, type, widget, color): if type == "QLabel": widget.setStyleSheet( "%s { background-color : %s; color : white; qproperty-alignment: AlignCenter; font: 15pt;}" % ( type, color)) else: widget.setStyleSheet("%s { background-color : %s; color : white; font: 15pt;}" % (type, color)) def ackTimeout(self, checkbox): if checkbox.isChecked(): if str(checkbox.text()) in self.timeout_ack: self.timeout_ack.remove(str(checkbox.text())) else: self.timeout_ack.append(str(checkbox.text())) def showWarning(self, attr): reply = QMessageBox.warning(self, 'Message', str(getattr(self, attr)), QMessageBox.Ok) def dialogTimeout(self): d = QDialog(self) d.setFixedWidth(450) d.setWindowTitle("Setting Devices Timeout") d.setVisible(True) vbox = QVBoxLayout() grid = QGridLayout() grid.setSpacing(20) for i, (key, value) in enumerate(self.parent.device_dict.iteritems()): checkbox = QCheckBox(key) checkbox.stateChanged.connect(partial(self.ackTimeout, checkbox)) checkbox.setCheckState(2) grid.addWidget(checkbox, 1 + i, 0, 1, 3) buttonBox = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel) buttonBox.button(QDialogButtonBox.Ok).clicked.connect(d.hide) buttonBox.button(QDialogButtonBox.Cancel).clicked.connect(d.hide) vbox.addLayout(grid) vbox.addWidget(buttonBox) d.setLayout(vbox) return d