def show(): message = "{0} {1} ".format(appinfo.appname, appinfo.version) pixmap = QPixmap(os.path.join(__path__[0], 'splash3.png')) if QApplication.desktop().screenGeometry().height() < 640: fontsize = 23 pixmap = pixmap.scaledToHeight(240, Qt.SmoothTransformation) else: fontsize = 40 splash = QSplashScreen(pixmap, Qt.SplashScreen) font = splash.font() font.setPixelSize(fontsize) font.setWeight(QFont.Bold) splash.setFont(font) splash.showMessage(message, Qt.AlignRight | Qt.AlignTop, Qt.white) splash.show() QApplication.processEvents() def hide(): splash.deleteLater() app.appStarted.disconnect(hide) app.appStarted.connect(hide)
def main(): import time os.chdir(civiltools_path) app = QtWidgets.QApplication(sys.argv) splash_pix = QPixmap("./images/civil-engineering.jpg") splash = QSplashScreen(splash_pix, Qt.WindowStaysOnTopHint) splash.setWindowFlags(Qt.WindowStaysOnTopHint | Qt.FramelessWindowHint) splash.setEnabled(False) # adding progress bar progressBar = QProgressBar(splash) progressBar.setMaximum(10) progressBar.setGeometry(50, splash_pix.height() - 30, splash_pix.width() - 100, 20) splash.show() splash.showMessage("<h1><font color='DarkRed'>civiltools by Ebrahim Raeyat Roknabadi </font></h1>", Qt.AlignCenter | Qt.AlignCenter, Qt.black) for i in range(1, 11): progressBar.setValue(i) t = time.time() while time.time() < t + 0.1: app.processEvents() # Simulate something that takes time time.sleep(1) # translator = QtCore.QTranslator() # translator.load("main_form.qm") # app.installTranslator(translator) window = FormWidget() window.setWindowTitle(_appname + ' ' + _version) window.show() splash.finish(window) sys.exit(app.exec_())
def main(): QtWidgets.QApplication.setAttribute(Qt.AA_EnableHighDpiScaling, True) # enable highdpi scaling Qt.HighDpiScaleFactorRoundingPolicy.Round scaleFactor = ctypes.windll.shcore.GetScaleFactorForDevice(0) / 100 if scaleFactor >= 1.5: os.environ["QT_SCREEN_SCALE_FACTORS"] = "1.5" else: os.environ[ "QT_SCREEN_SCALE_FACTORS"] = "scaleFactor" # das ist der richtige Skalierungsfaktor #os.environ["QT_AUTO_SCREEN_SCALE_FACTOR"] = "-1" #QT_SCREEN_SCALE_FACTORS #os.environ["QT_SCALE_FACTOR"] = "1.4" #os.environ["QT_DEVICE_PIXEL_RATIO"] = "0.5" app = QApplication(sys.argv) pixmap = QPixmap(os.path.dirname(sys.argv[0]) + "/pics/splesh.JPG") splash = QSplashScreen(pixmap) splash.show() splash.showMessage("Module werden geladen...") app.processEvents() app.setStyle("Fusion") time.sleep(3) window11 = myTab5.myTab5() #window11.setFixedSize(1100, 600) #window11.resize(window11.minimumSizeHint()) splash.finish(window11) showForUpdates(version, "https://digital-ies.de/wp-content/uploads", app, window11) app.exec_()
def main(): # define command line parameters parser = ArgumentParser() parser.add_argument("--no-splash", dest="splash", action="store_false") args = parser.parse_args() app = QApplication(sys.argv) # create splash screen with sponsors # default splash=True, use "-s" or "--splash" to set splash=False window = MainWindow() if args.splash: pixmap = QPixmap(os.path.join("resources","splash", "splash.jpg")) splash = QSplashScreen(pixmap) splash.showMessage(" Version: " + __version__, Qt.AlignBottom) # show the splash screen for 3 seconds splash.show() app.processEvents() QThread.sleep(3) window.show() splash.finish(window) else: window.show() sys.exit(app.exec())
def main(test_func): from pyminer2 import pmutil app = QApplication(sys.argv) path_logo = os.path.join(pmutil.get_root_dir(), r'ui\source\icons\logo.png') app.setWindowIcon(QIcon(path_logo)) # 设置应用logo path_splash = os.path.join(pmutil.get_root_dir(), r'ui\source\images\splash.png') splash = QSplashScreen(QPixmap(path_splash)) splash.showMessage("正在加载pyminer... 0%", Qt.AlignHCenter | Qt.AlignBottom, Qt.black) splash.show() # 显示启动界面 pmutil._application = app load_fonts(app) load_translator(app) # font = os.path.join(os.path.dirname(__file__), 'ui', 'source', 'font', 'SourceCodePro-Regular.ttf') app.default_font = 'Deng' f = QFont(app.default_font, 10) app.setFont(f) demo = MainWindow() demo.events_ready_signal.connect(test_func) splash.finish(demo) # 修复故障 I1VYVO 程序启动完成后,关闭启动界面 liugang 20200921 id(demo) sys.exit(app.exec_())
class GtoSplasher: def __init__(self, info): try: self.info = info self.splasher = None self.info.iface.mainWindow().showMinimized() qgisAppDataPath = QStandardPaths.standardLocations( QStandardPaths.AppDataLocation)[0] file = os.path.join(qgisAppDataPath, "splash.png") if not os.path.isfile(file): file = os.path.join(os.path.dirname(__file__), "splash.png") if os.path.isfile(file): pixmap = QPixmap(file) self.splasher = QSplashScreen(pixmap, Qt.WindowStaysOnTopHint) self.splasher.setPixmap(pixmap) self.splasher.show() except Exception as e: self.info.err(e) def log(self, msg): try: if self.splasher is not None: self.splasher.show() self.splasher.showMessage(msg, Qt.AlignCenter | Qt.AlignBottom) QApplication.instance().processEvents() self.info.log('Splasher:', msg) except Exception as e: self.info.err(e) def close(self): if self.splasher is not None: self.splasher.close()
def showSplashScreen(): splash_path = os.path.join(os.path.split(ilastik.__file__)[0], 'ilastik-splash.png') splashImage = QPixmap(splash_path) global splashScreen splashScreen = QSplashScreen(splashImage) splashScreen.showMessage( ilastik.__version__, Qt.AlignBottom | Qt.AlignRight ) splashScreen.show()
def showMessage(self, msg): """Procedure to update message in splash""" align = Qt.Alignment(Qt.AlignBottom | Qt.AlignRight | Qt.AlignAbsolute) # color = QtGui.QColor(QtCore.Qt.White) color = QColor(0, 0, 0) QSplashScreen.showMessage(self, msg, align, color) QApplication.processEvents()
class SplashScreen: def __init__(self, parent, image=None, after=None): self.app = parent image = QPixmap(image) image = image.scaled(500, 500, Qt.KeepAspectRatio, Qt.SmoothTransformation) self.splash = QSplashScreen( image, Qt.FramelessWindowHint | Qt.WindowStaysOnTopHint) self.splash.setMask(image.mask()) self.after = after def set_after(self, after): self.after = after def __enter__(self): self.splash.show() self.app.processEvents() return self def __exit__(self, exc_type, exc_value, traceback): self.after.show() self.splash.finish(self.after) def status_update(self, msg): self.splash.showMessage(msg, alignment=Qt.AlignHCenter, color=QColor(235, 239, 242)) self.app.processEvents()
def showMessage(self, msg): """ Public method to show a message in the bottom part of the splashscreen. @param msg message to be shown (string or QString) """ QSplashScreen.showMessage( self, msg, self.labelAlignment, QColor(Qt.white)) QApplication.processEvents()
def showSplashScreen(): splash_path = os.path.join( os.path.split(ilastik.__file__)[0], 'ilastik-splash.png') splashImage = QPixmap(splash_path) global splashScreen splashScreen = QSplashScreen(splashImage) splashScreen.showMessage(ilastik.__version__, Qt.AlignBottom | Qt.AlignRight) splashScreen.show()
def start_process(self): splash = QSplashScreen(QtGui.QPixmap(os.path.join(self.root_dir,"logo/logo-upper.ico"))) splash.showMessage("... 0%", QtCore.Qt.AlignHCenter | QtCore.Qt.AlignBottom, QtCore.Qt.black) splash.resize(200,90) splash.show() QtWidgets.qApp.processEvents() self.progress(splash) splash.show() splash.finish(self)
def showMessage(self, message, *args): """ Public method to show a message in the bottom part of the splashscreen. @param message message to be shown (string or QString) """ QSplashScreen.showMessage( self, message, Qt.AlignBottom | Qt.AlignRight | Qt.AlignAbsolute, QColor(Qt.white))
def start_animation(): splash = QSplashScreen() splash.setPixmap(QPixmap('images/zyx1.jpg')) splash.show() font = QFont("微软雅黑",16) splash.setFont(font) splash.showMessage('<font color="blue" size="16">Welcome to Use This PyQt5-Made Notebook~ <br> 向为喜爱的创造一切,不想不爱的人解释一句~</font>', Qt.AlignBottom | Qt.AlignCenter, Qt.white) #splash.setFont(QFont("microsoft yahei", 20, QFont::Bold)) time.sleep(2)
def showMessage(self, message, alignment=Qt.AlignLeft, color=Qt.black): """ Show the `message` with `color` and `alignment`. """ # Need to store all this arguments for drawContents (no access # methods) self.__alignment = alignment self.__color = color self.__message = message QSplashScreen.showMessage(self, message, alignment, color) QApplication.instance().processEvents()
class LoadingUI(object): def __init__(self, main_window: QMainWindow): """ 启动动画 """ self.main_window = main_window self.splash = QSplashScreen() def setup_ui(self) -> None: font = QFont() font.setPointSize(12) self.splash.setFont(font) # 因为QSplashScreen类实现的组件本身就是无边框界面所以我们可以省略Qt::FramelessWindowHint # self.splash.setWindowFlags(Qt.WindowStaysOnTopHint | Qt.FramelessWindowHint) # 正确的写法是只添加Qt::WindowStaysOnTopHint标志 # setWindowFlags(Qt.WindowStaysOnTopHint) # 设置全屏显示 # self.splash.showFullScreen() # 加载图片 # self.splash.setPixmap(QPixmap(":/images/loading.png")) # self.splash.setPixmap(QPixmap(settings.MAIN_UI["background"])) self.splash.setPixmap(QPixmap(settings.MAIN_UI["loading"])) # 显示信息 self.splash.showMessage("系统正在启动中...", Qt.AlignHCenter | Qt.AlignBottom, Qt.white) # self.splash.showMessage("加载... 0%", Qt.AlignHCenter | Qt.AlignBottom, Qt.white) logger.debug("系统正在启动中...") self.splash.show() # 显示启动界面 # qApp.processEvents() # 允许主进程处理事件 # 加载数据 # self.load_data() # self.main_window.show() # self.splash.finish(self.main_window) # 隐藏启动界面 def load_data(self) -> None: """ 模拟加载数据 :return: """ for i in range(1, 5): # 模拟主程序加载过程 # time.sleep(1) # 加载数据 msg = "加载... {0}%".format(i * 10) self.splash.showMessage(msg, Qt.AlignHCenter | Qt.AlignBottom, Qt.red) logger.debug(msg) qApp.processEvents() # 允许主进程处理事件
def main(): app = QApplication(sys.argv) ash = QSplashScreen(QtGui.QPixmap("UI/NUI.png")) ash.setFont(QtGui.QFont('Microsoft YaHei UI',20)) ash.show() ash.showMessage("系统启动中,请稍候",QtCore.Qt.AlignLeft | QtCore.Qt.AlignBottom, QtCore.Qt.green) main_window = MainWindow() # app.setStyleSheet(qdarkstyle.load_stylesheet_pyqt5()) main_window.show() ash.finish(main_window) sys.exit(app.exec_())
def send_command(self, command): try: pixmap = QPixmap("Design/loading.jpg") pixmap = pixmap.scaled(520, 350) splash = QSplashScreen(pixmap, Qt.WindowStaysOnTopHint) splash.show() splash.showMessage("") #Wait until all hosts have connected (or failed). [thread.join() for thread in host_threads] stdin, stdout, stderr = self.session.exec_command(command) #print(stderr.readlines()) return stdout.readlines() except Exception as ex: print("Error executing commands...") print(ex)
def showSplash(self): # Create and display the splash screen splash_pix = QPixmap( 'C:\\Users\\vcone\\Desktop\\Cosas\\CS\\Software2\\GUI test\\pick-tool-team13-the-bombs\\loading.png' ) splash = QSplashScreen(splash_pix, Qt.WindowStaysOnTopHint) splash.setMask(splash_pix.mask()) # Show a message at the center of the dialog splash.showMessage("Cleansing", 0x0084) splash.show() app.processEvents() # Simulate something that takes time time.sleep(2) splash.finish(self)
def splashScreen(app, version) -> QSplashScreen: # This first part is for loading the splash screen before anything else # Create and display the splash screen splash_pix = QPixmap(ARTWORK_DIR_NAME + 'SplashScreen.png') splash = QSplashScreen(splash_pix, Qt.WindowStaysOnTopHint) splash.showMessage('Version %s\n' % version, alignment=Qt.AlignHCenter + Qt.AlignBottom, color=Qt.black) splash.setMask(splash_pix.mask()) splash.show() app.processEvents() return splash
def show_splash(text: str) -> QSplashScreen: splash = QSplashScreen() splash_font = QFont() # splashFont.setFamily("Arial") splash_font.setBold(True) splash_font.setPixelSize(16) splash_font.setStretch(120) splash.setWindowFlags(Qt.WindowStaysOnTopHint | Qt.SplashScreen) splash = QSplashScreen() splash.show() splash.setStyleSheet("background-color:#fcc77c;") splash.setFont(splash_font) splash.setMinimumWidth(400) splash.setMaximumHeight(100) splash.showMessage(text, alignment=Qt.AlignCenter, ) return splash
def show_splash_screen(): from PyQt5.QtWidgets import QSplashScreen from PyQt5.QtGui import QPixmap, QColor from PyQt5.QtCore import Qt # create and display the splash screen splash_pix = QPixmap('assets/splash.jpg') splash = QSplashScreen(splash_pix, Qt.WindowStaysOnTopHint) splash.setMask(splash_pix.mask()) splash.showMessage('Loading...', alignment=Qt.AlignCenter | Qt.AlignBottom, color=QColor(Qt.white)) splash.show() return splash
def start_main_window(): App = QApplication(sys.argv) #Загружаем заставку. splash = QSplashScreen(QtGui.QPixmap('/home/denis-linux/Загрузки/444.jpg')) splash.showMessage('Загрузка данных .... 0%', QtCore.Qt.AlignCenter | QtCore.Qt.AlignBottom, QtCore.Qt.red) splash.setGeometry(320, 320, 600, 400) splash.pixmap() # ОТображаем заставку splash.show() # Запускаем оборотный цикл App.processEvents() window = Window() window.load_data(splash) window.show() splash.finish(window) sys.exit(App.exec_())
def main(): app = QApplication(sys.argv) app.setStyle("Fusion") app.setStyleSheet("QPushButton { margin: 200ex; }") dark_palette = QPalette() dark_palette.setColor(QPalette.Window, QColor(53, 53, 53)) dark_palette.setColor(QPalette.WindowText, Qt.white) dark_palette.setColor(QPalette.Base, QColor(25, 25, 25)) dark_palette.setColor(QPalette.AlternateBase, QColor(53, 53, 53)) dark_palette.setColor(QPalette.ToolTipBase, Qt.white) dark_palette.setColor(QPalette.ToolTipText, Qt.white) dark_palette.setColor(QPalette.Text, Qt.white) dark_palette.setColor(QPalette.Button, QColor(53, 53, 53)) dark_palette.setColor(QPalette.ButtonText, Qt.white) dark_palette.setColor(QPalette.BrightText, Qt.red) dark_palette.setColor(QPalette.Link, QColor(42, 130, 218)) dark_palette.setColor(QPalette.Highlight, QColor(42, 130, 218)) dark_palette.setColor(QPalette.HighlightedText, Qt.black) app.setPalette(dark_palette) splash_pix = QPixmap('splash.png') splash = QSplashScreen(splash_pix, Qt.WindowStaysOnTopHint) splash.setWindowFlags(Qt.WindowStaysOnTopHint | Qt.FramelessWindowHint) splash.setEnabled(False) progressBar = QProgressBar(splash) progressBar.setMaximum(10) progressBar.setGeometry(0, splash_pix.height() - 50, splash_pix.width(), 20) splash.show() splash.showMessage("<h1><font color='green'>Welcome!</font></h1>", Qt.AlignTop | Qt.AlignCenter, Qt.black) for i in range(1, 11): progressBar.setValue(i) t = time.time() while time.time() < t + 0.1: app.processEvents() time.sleep(2) splash.close() controller = Controller() controller.show_first() sys.exit(app.exec_())
def aboutDialog(app, version): # Create and display the about screen splash_pix = QPixmap(ARTWORK_DIR_NAME + 'AboutScreen.png') splash = QSplashScreen(splash_pix, Qt.WindowStaysOnTopHint) splash.showMessage('Version %s\n' % version, alignment=Qt.AlignHCenter + Qt.AlignBottom, color=Qt.black) splash.setMask(splash_pix.mask()) splash.show() splash.mousePressEvent = partial(closeDlg, splash) start = time() while splash.isActiveWindow() & (time() - start < 10): sleep(0.001) app.processEvents() if (splash.isActiveWindow()): splash.close()
def main(): from pyminer2 import pmutil app = QApplication(sys.argv) path_logo = os.path.dirname(os.path.abspath(__file__)) + r'\ui\source\icons\logo.png' app.setWindowIcon(QIcon(path_logo)) # 设置应用logo path_splash = os.path.dirname(os.path.abspath(__file__)) + r'\ui\source\images\splash.png' splash = QSplashScreen(QPixmap(path_splash)) splash.showMessage("正在加载pyminer... 0%", Qt.AlignHCenter | Qt.AlignBottom, Qt.black) splash.show() # 显示启动界面 app.splash = splash pmutil._application = app load_fonts(app) load_translator(app) app.default_font = 'Deng' f = QFont(app.default_font, 10) app.setFont(f) demo = MainWindow() splash.finish(demo) # 修复故障 I1VYVO 程序启动完成后,关闭启动界面 liugang 20200921 id(demo) sys.exit(app.exec_())
def inital1(self): try: # Check for root dir in start file with open('start') as fp: self.path = fp.read() print(self.path) if self.path=='': raise ("Invalid file name") except: widget = QDialog(self) ui = Ui_Setting() # ui.path = self.path ui.setupUi(widget) print(path) widget.exec_() self.path = path if not os.path.exists(self.path): exit(-1) else: with open('start', 'w') as fp: fp.write(self.path) pixmap = QPixmap("new.png") splash = QSplashScreen(pixmap) splash.showMessage("Loading...") app.processEvents() splash.show() # Call the database class db = database.Network(self.path) db.start() self.db = db print(db.database) # # finish the splash screen splash.finish(self)
def main(args=None): # supply path to qgis install location QgsApplication.setPrefixPath("/usr", True) # create a reference to the QgsApplication # setting the second argument to True enables the IquaView GUI, # which we need to do since this is a custom application qgs = QgsApplication([], True) # init splash screen splash_pix = QPixmap(':/resources/iquaview.png') splash = QSplashScreen(splash_pix, Qt.WindowStaysOnTopHint) splash.setMask(splash_pix.mask()) light_blue = QColor(165, 197, 192) dark_blue = QColor(11, 52, 70) # adding progress bar progress_bar = QProgressBar(splash) p = progress_bar.palette() p.setColor(QPalette.Highlight, light_blue) p.setColor(QPalette.HighlightedText, dark_blue) progress_bar.setPalette(p) progress_bar.setMaximum(10) progress_bar.setGeometry(0, splash_pix.height() - 50, splash_pix.width(), 20) splash.show() splash.showMessage("Initializing interface...", Qt.AlignBottom | Qt.AlignCenter, light_blue) # progress bar... for i in range(1, 11): progress_bar.setValue(i) t = time() if i == 5: splash.showMessage("Loading providers...", Qt.AlignBottom | Qt.AlignCenter, light_blue) # load providers qgs.initQgis() LOGGER.info(qgs.showSettings()) if i == 10: # exec iquaview window window = MainWindow() window.setWindowIcon(QIcon(":/resources/iquaview_vector.svg")) splash.showMessage("IQUAview ready!", Qt.AlignBottom | Qt.AlignCenter, light_blue) while time() < t + 0.1: qgs.processEvents() window.showMaximized() splash.finish(window) qgs.exec_() window.deleteLater() # when app terminates, call exitQgis() to remove the provider and layer registries from memory qgs.exitQgis()
def start(self): if self.run_flag == True : return self.updateCamFlagInfo() #self.database.updataOpenflag('cam_01',1) #self.database.updataOpenflag('cam_02',1) #self.database.updataOpenflag('cam_03',1) if(self.cam_01 or self.cam_02 or self.cam_03): ash = QSplashScreen(QtGui.QPixmap("UI/NUI.png")) ash.setFont(QtGui.QFont('Microsoft YaHei UI',20)) ash.show() ash.showMessage("摄像头链接中,请稍候",QtCore.Qt.AlignLeft | QtCore.Qt.AlignBottom, QtCore.Qt.green) self.updateCamInfo() self.run_flag = True if (self.cam_01 == True and self.vs1.isOpened() == False) or (self.cam_02 == True and self.vs2.isOpened() == False) or (self.cam_03 == True and self.vs3.isOpened() == False): self.run_flag = False ash.close() res = QMessageBox.question(self,'警告','摄像头链接失败,请核对摄像头参数') else: ash.close() else: res = QMessageBox.question(self,'警告','请先设置摄像头参数')
class LoadingWindow(QWidget): #创建用户界面的基类 def __init__(self): super().__init__() self.initUI('image\loading.png') self.show() self.splash.finish(self) def initUI(self, img): print('starting program') self.splash = QSplashScreen( QPixmap(img)) #QSplashScreen是Qt提供一个一个载入界面程序 # QPixmap缩放图像,专门为图像在屏幕上的显示做了优化 self.splash.showMessage('加载。。0%', Qt.AlignHCenter | Qt.AlignBottom, Qt.white) self.splash.show() #显示控件 qApp.processEvents() self.load_data() def load_data(self): for i in range(1, 11): time.sleep(0.1) self.splash.showMessage("加载。。{0}%".format(i * 10), Qt.AlignHCenter | Qt.AlignBottom, Qt.white) qApp.processEvents() # def loading(): # print('starting program') # splash = QSplashScreen(QPixmap()) # # splash.showMessage('加载。。0%', Qt.AlignHCenter | Qt.AlignBottom, Qt.white) # splash.show() # qApp.processEvents() # window1 = LoadingWindow() # window1.load_data(splash) # window1.show() # splash.finish(window1)
class QtApplication(QApplication, Application, SignalEmitter): def __init__(self, **kwargs): plugin_path = "" if sys.platform == "win32": plugin_path = os.path.join(os.path.dirname(os.path.abspath(sys.executable)), "PyQt5", "plugins") Logger.log("i", "Adding QT5 plugin path: %s" % (plugin_path)) QCoreApplication.addLibraryPath(plugin_path) elif sys.platform == "darwin": plugin_path = os.path.join(Application.getInstallPrefix(), "Resources", "plugins") if plugin_path: Logger.log("i", "Adding QT5 plugin path: %s" % (plugin_path)) QCoreApplication.addLibraryPath(plugin_path) os.environ["QSG_RENDER_LOOP"] = "basic" super().__init__(sys.argv, **kwargs) self._main_qml = "main.qml" self._engine = None self._renderer = None try: self._splash = QSplashScreen(QPixmap(Resources.getPath(Resources.ImagesLocation, self.getApplicationName() + ".png"))) except FileNotFoundError: self._splash = None else: self._splash.show() self.processEvents() signal.signal(signal.SIGINT, signal.SIG_DFL) # This is done here as a lot of plugins require a correct gl context. If you want to change the framework, # these checks need to be done in your <framework>Application.py class __init__(). i18n_catalog = i18nCatalog("uranium") self.showSplashMessage(i18n_catalog.i18nc("Splash screen message", "Loading plugins...")) self._loadPlugins() self._plugin_registry.checkRequiredPlugins(self.getRequiredPlugins()) self.showSplashMessage(i18n_catalog.i18nc("Splash screen message", "Loading machines...")) self.loadMachines() self.showSplashMessage(i18n_catalog.i18nc("Splash screen message", "Loading preferences...")) try: file = Resources.getPath(Resources.PreferencesLocation, self.getApplicationName() + ".cfg") Preferences.getInstance().readFromFile(file) except FileNotFoundError: pass self._translators = {} self.showSplashMessage(i18n_catalog.i18nc("Splash screen message", "Loading translations...")) self.loadQtTranslation("uranium_qt") self.loadQtTranslation(self.getApplicationName() + "_qt") def run(self): pass def hideMessage(self, message): with self._message_lock: if message in self._visible_messages: self._visible_messages.remove(message) self.visibleMessageRemoved.emit(message) def showMessage(self, message): with self._message_lock: if message not in self._visible_messages: self._visible_messages.append(message) message.setTimer(QTimer()) self.visibleMessageAdded.emit(message) pass def setMainQml(self, path): self._main_qml = path def initializeEngine(self): # TODO: Document native/qml import trickery Bindings.register() self._engine = QQmlApplicationEngine() self.engineCreatedSignal.emit() self._engine.addImportPath(os.path.join(os.path.dirname(sys.executable), "qml")) self._engine.addImportPath(os.path.join(Application.getInstallPrefix(), "Resources", "qml")) if not hasattr(sys, "frozen"): self._engine.addImportPath(os.path.join(os.path.dirname(__file__), "qml")) self.registerObjects(self._engine) self._engine.load(self._main_qml) engineCreatedSignal = Signal() def registerObjects(self, engine): pass def getRenderer(self): if not self._renderer: self._renderer = QtGL2Renderer() return self._renderer # Overridden from QApplication::setApplicationName to call our internal setApplicationName def setApplicationName(self, name): Application.setApplicationName(self, name) # Handle a function that should be called later. def functionEvent(self, event): e = _QtFunctionEvent(event) QCoreApplication.postEvent(self, e) # Handle Qt events def event(self, event): if event.type() == _QtFunctionEvent.QtFunctionEvent: event._function_event.call() return True return super().event(event) def windowClosed(self): self.getBackend().close() self.quit() self.saveMachines() Preferences.getInstance().writeToFile(Resources.getStoragePath(Resources.PreferencesLocation, self.getApplicationName() + ".cfg")) ## Load a Qt translation catalog. # # This method will locate, load and install a Qt message catalog that can be used # by Qt's translation system, like qsTr() in QML files. # # \param file The file name to load, without extension. It will be searched for in # the i18nLocation Resources directory. If it can not be found a warning # will be logged but no error will be thrown. # \param language The language to load translations for. This can be any valid language code # or 'default' in which case the language is looked up based on system locale. # If the specified language can not be found, this method will fall back to # loading the english translations file. # # \note When `language` is `default`, the language to load can be changed with the # environment variable "LANGUAGE". def loadQtTranslation(self, file, language = "default"): #TODO Add support for specifying a language from preferences path = None if language == "default": # If we have a language set in the environment, try and use that. lang = os.getenv("LANGUAGE") if lang: try: path = Resources.getPath(Resources.i18nLocation, lang, "LC_MESSAGES", file + ".qm") except FileNotFoundError: path = None # If looking up the language from the enviroment fails, try and use Qt's system locale instead. if not path: locale = QLocale.system() # First, try and find a directory for any of the provided languages for lang in locale.uiLanguages(): try: path = Resources.getPath(Resources.i18nLocation, lang, "LC_MESSAGES", file + ".qm") language = lang except FileNotFoundError: pass else: break # If that fails, see if we can extract a language "class" from the # preferred language. This will turn "en-GB" into "en" for example. if not path: lang = locale.uiLanguages()[0] lang = lang[0:lang.find("-")] try: path = Resources.getPath(Resources.i18nLocation, lang, "LC_MESSAGES", file + ".qm") language = lang except FileNotFoundError: pass else: path = Resources.getPath(Resources.i18nLocation, language, "LC_MESSAGES", file + ".qm") # If all else fails, fall back to english. if not path: Logger.log("w", "Could not find any translations matching {0} for file {1}, falling back to english".format(language, file)) try: path = Resources.getPath(Resources.i18nLocation, "en", "LC_MESSAGES", file + ".qm") except FileNotFoundError: Logger.log("w", "Could not find English translations for file {0}. Switching to developer english.".format(file)) return translator = QTranslator() if not translator.load(path): Logger.log("e", "Unable to load translations %s", file) return # Store a reference to the translator. # This prevents the translator from being destroyed before Qt has a chance to use it. self._translators[file] = translator # Finally, install the translator so Qt can use it. self.installTranslator(translator) ## Display text on the splash screen. def showSplashMessage(self, message): if self._splash: self._splash.showMessage(message , Qt.AlignHCenter | Qt.AlignVCenter) self.processEvents() ## Close the splash screen after the application has started. def closeSplash(self): if self._splash: self._splash.close() self._splash = None
def main(): print("Platform is %s (%s)" %(platform.system(), sys.platform)) if platform.system() == "Windows": print("Applying Windows-specific setup") # On Windows, redirect stderr to a file import imp import ctypes if (hasattr(sys, "frozen") or # new py2exe hasattr(sys, "importers") or # old py2exe imp.is_frozen("__main__")): # tools/freeze sys.stderr = open(os.path.expanduser("~/friture.exe.log"), "w") # set the App ID for Windows 7 to properly display the icon in the # taskbar. myappid = 'Friture.Friture.Friture.current' # arbitrary string try: ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID(myappid) except: print("Could not set the app model ID. If the plaftorm is older than Windows 7, this is normal.") app = QApplication(sys.argv) if platform.system() == "Darwin": if hasattr(sys, "frozen"): #py2app sys.stdout = open(os.path.expanduser("~/friture.out.txt"), "w") sys.stderr = open(os.path.expanduser("~/friture.err.txt"), "w") print("Applying Mac OS-specific setup") # help the py2app-packaged application find the Qt plugins (imageformats and platforms) pluginsPath = os.path.normpath(os.path.join(QApplication.applicationDirPath(), os.path.pardir, 'PlugIns')) print("Adding the following to the Library paths: " + pluginsPath) QApplication.addLibraryPath(pluginsPath) # Splash screen pixmap = QPixmap(":/images/splash.png") splash = QSplashScreen(pixmap) splash.show() splash.showMessage("Initializing the audio subsystem") app.processEvents() # Logger class logger = Logger() window = Friture(logger) window.show() splash.finish(window) profile = "no" # "python" or "kcachegrind" or anything else to disable if len(sys.argv) > 1: if sys.argv[1] == "--python": profile = "python" elif sys.argv[1] == "--kcachegrind": profile = "kcachegrind" elif sys.argv[1] == "--no": profile = "no" else: print("command-line arguments (%s) not recognized" % sys.argv[1:]) if profile == "python": import cProfile import pstats cProfile.runctx('app.exec_()', globals(), locals(), filename="friture.cprof") stats = pstats.Stats("friture.cprof") stats.strip_dirs().sort_stats('time').print_stats(20) stats.strip_dirs().sort_stats('cumulative').print_stats(20) sys.exit(0) elif profile == "kcachegrind": import cProfile import lsprofcalltree p = cProfile.Profile() p.run('app.exec_()') k = lsprofcalltree.KCacheGrind(p) with open('cachegrind.out.00000', 'wb') as data: k.output(data) sys.exit(0) else: sys.exit(app.exec_())
def start(filenames=None, projects_path=None, extra_plugins=None, linenos=None): app = QApplication(sys.argv) QCoreApplication.setOrganizationName('NINJA-IDE') QCoreApplication.setOrganizationDomain('NINJA-IDE') QCoreApplication.setApplicationName('NINJA-IDE') app.setWindowIcon(QIcon(resources.IMAGES['icon'])) # Check if there is another session of ninja-ide opened # and in that case send the filenames and projects to that session running = ipc.is_running() start_server = not running[0] if running[0] and (filenames or projects_path): sended = ipc.send_data(running[1], filenames, projects_path, linenos) running[1].close() if sended: sys.exit() else: running[1].close() # Create and display the splash screen splash_pix = QPixmap(resources.IMAGES['splash']) splash = QSplashScreen(splash_pix, Qt.WindowStaysOnTopHint) splash.setMask(splash_pix.mask()) splash.show() app.processEvents() # Set the cursor to unblinking if sys.platform != 'win32': app.setCursorFlashTime(0) #Set the codec for strings (QString) print("codec:", QTextCodec.codecForName('utf-8')) #QTextCodec.setCodecForCStrings(QTextCodec.codecForName('utf-8')) #Translator #qsettings = QSettings() qsettings = QSettings(resources.SETTINGS_PATH, QSettings.IniFormat) language = QLocale.system().name() lang = qsettings.value('preferences/interface/language', defaultValue=language, type='QString') + '.qm' lang_path = file_manager.create_path(resources.LANGS, lang) if file_manager.file_exists(lang_path): settings.LANGUAGE = lang_path elif file_manager.file_exists(file_manager.create_path( resources.LANGS_DOWNLOAD, lang)): settings.LANGUAGE = file_manager.create_path( resources.LANGS_DOWNLOAD, lang) translator = QTranslator() if settings.LANGUAGE: translator.load(settings.LANGUAGE) app.installTranslator(translator) qtTranslator = QTranslator() qtTranslator.load("qt_" + language, QLibraryInfo.location(QLibraryInfo.TranslationsPath)) app.installTranslator(qtTranslator) #Loading Syntax splash.showMessage("Loading Syntax", Qt.AlignRight | Qt.AlignTop, Qt.black) json_manager.load_syntax() #Read Settings splash.showMessage("Loading Settings", Qt.AlignRight | Qt.AlignTop, Qt.black) settings.load_settings() #Set Stylesheet style_applied = False if settings.NINJA_SKIN not in ('Default', 'Classic Theme'): file_name = ("%s.qss" % settings.NINJA_SKIN) qss_file = file_manager.create_path(resources.NINJA_THEME_DOWNLOAD, file_name) if file_manager.file_exists(qss_file): with open(qss_file) as f: qss = f.read() app.setStyleSheet(qss) style_applied = True if not style_applied: if settings.NINJA_SKIN == 'Default': with open(resources.NINJA_THEME) as f: qss = f.read() else: with open(resources.NINJA__THEME_CLASSIC) as f: qss = f.read() app.setStyleSheet(qss) #Loading Schemes splash.showMessage("Loading Schemes", Qt.AlignRight | Qt.AlignTop, Qt.black) scheme = qsettings.value('preferences/editor/scheme', "default", type='QString') if scheme != 'default': scheme = file_manager.create_path(resources.EDITOR_SKINS, scheme + '.color') if file_manager.file_exists(scheme): resources.CUSTOM_SCHEME = json_manager.parse(open(scheme)) #Loading Shortcuts resources.load_shortcuts() #Loading GUI splash.showMessage("Loading GUI", Qt.AlignRight | Qt.AlignTop, Qt.black) ide = IDE(start_server) #Showing GUI ide.show() #Loading Session Files splash.showMessage("Loading Files and Projects", Qt.AlignRight | Qt.AlignTop, Qt.black) #Files in Main Tab main_files = qsettings.value('openFiles/mainTab', []) if main_files is not None: mainFiles = list(main_files) else: mainFiles = list() tempFiles = [] for file_ in mainFiles: fileData = list(file_) if fileData: lineno = fileData[1] tempFiles.append((fileData[0], lineno)) mainFiles = tempFiles #Files in Secondary Tab sec_files = qsettings.value('openFiles/secondaryTab', []) if sec_files is not None: secondaryFiles = list(sec_files) else: secondaryFiles = list() tempFiles = [] for file_ in secondaryFiles: fileData = list(file_) lineno = fileData[1] tempFiles.append((fileData[0], lineno)) secondaryFiles = tempFiles # Recent Files recent = qsettings.value('openFiles/recentFiles', []) if recent is not None: recent_files = list(recent) else: recent_files = list() recent_files = [file_ for file_ in recent_files] #Current File current_file = qsettings.value('openFiles/currentFile', '', type='QString') #Projects projects_list = qsettings.value('openFiles/projects', []) if projects_list is not None: projects = list(projects_list) else: projects = list() projects = [project for project in projects] #Include files received from console args file_with_nro = list([(f[0], f[1] - 1) for f in zip(filenames, linenos)]) file_without_nro = list([(f, 0) for f in filenames[len(linenos):]]) mainFiles += file_with_nro + file_without_nro #Include projects received from console args if projects_path: projects += projects_path ide.load_session_files_projects(mainFiles, secondaryFiles, projects, current_file, recent_files) #Load external plugins if extra_plugins: ide.load_external_plugins(extra_plugins) splash.finish(ide) ide.notify_plugin_errors() ide.show_python_detection() sys.exit(app.exec_())
def main(): if platform.system() == "Windows": print("Running on Windows") # On Windows, redirect stderr to a file import imp, ctypes if (hasattr(sys, "frozen") or # new py2exe hasattr(sys, "importers") or # old py2exe imp.is_frozen("__main__")): # tools/freeze sys.stderr = open(os.path.expanduser("~/friture.exe.log"), "w") # set the App ID for Windows 7 to properly display the icon in the # taskbar. myappid = 'Friture.Friture.Friture.current' # arbitrary string try: ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID(myappid) except: print("Could not set the app model ID. If the plaftorm is older than Windows 7, this is normal.") app = QApplication(sys.argv) # Splash screen pixmap = QPixmap(":/images/splash.png") splash = QSplashScreen(pixmap) splash.show() splash.showMessage("Initializing the audio subsystem") app.processEvents() # Set the separator stylesheet here # As of Qt 4.6, separator width is not handled correctly # when the stylesheet is applied directly to the QMainWindow instance. # QtCreator workarounds it with a "minisplitter" special class app.setStyleSheet(STYLESHEET) # Logger class logger = Logger() window = Friture(logger) window.show() splash.finish(window) profile = "no" # "python" or "kcachegrind" or anything else to disable if len(sys.argv) > 1: if sys.argv[1] == "--python": profile = "python" #elif sys.argv[1] == "--kcachegrind": #profile = "kcachegrind" elif sys.argv[1] == "--no": profile = "no" else: print("command-line arguments (%s) not recognized" %sys.argv[1:]) if profile == "python": import cProfile import pstats cProfile.runctx('app.exec_()', globals(), locals(), filename="friture.cprof") stats = pstats.Stats("friture.cprof") stats.strip_dirs().sort_stats('time').print_stats(20) stats.strip_dirs().sort_stats('cumulative').print_stats(20) sys.exit(0) #elif profile == "kcachegrind": #import cProfile #import lsprofcalltree #p = cProfile.Profile() #p.run('app.exec_()') #k = lsprofcalltree.KCacheGrind(p) #data = open('cachegrind.out.00000', 'wb') #k.output(data) #data.close() ## alternative code with pyprof2calltree instead of lsprofcalltree ##import pyprof2calltree ##pyprof2calltree.convert(p.getstats(), "cachegrind.out.00000") # save #sys.exit(0) else: sys.exit(app.exec_())
def main(): try: locale.setlocale(locale.LC_ALL, '') except locale.Error: pass # ignore this as it might fail on macOS, we'll fallback to UTF-8 in that case if config.get_use_fusion_gui_style(): sys.argv += ['-style', 'fusion'] if '--error-report' in sys.argv: sys.exit(error_report_main()) # Catch all uncaught exceptions and show an error message for them. # PyQt5 does not silence exceptions in slots (as did PyQt4), so there # can be slots which try to (for example) send requests but don't wrap # them in an async call with error handling. argv = deepcopy(sys.argv) # Deep copy because QApplication (i.e. BrickViewer) constructor parses away Qt args and we want to know the style. if '--no-error-reporter' not in sys.argv: ExceptionReporter(argv) # Exceptions that happen before the event loop runs (f.e. syntax errors) kill the brickv so fast, that the error reporter thread # (which is daemonized) can not report the error before it is killed. Report them manually. try: # importing the MainWindow after creating the QApplication instance triggers this warning # # Qt WebEngine seems to be initialized from a plugin. Please set Qt::AA_ShareOpenGLContexts # using QCoreApplication::setAttribute before constructing QGuiApplication. # # do what the warnings says to avoid it QApplication.setAttribute(Qt.AA_ShareOpenGLContexts) brick_viewer = BrickViewer(sys.argv) if sys.platform == 'darwin': # workaround macOS QTBUG-61562 from brickv.mac_pasteboard_mime_fixed import MacPasteboardMimeFixed mac_pasteboard_mime_fixed = MacPasteboardMimeFixed() splash = QSplashScreen(load_pixmap('splash.png'), Qt.WindowStaysOnTopHint) splash.show() message = 'Starting Brick Viewer ' + config.BRICKV_VERSION if config.INTERNAL != None: message += '~{}'.format(config.INTERNAL) splash.showMessage(message, Qt.AlignHCenter | Qt.AlignBottom, Qt.white) brick_viewer.processEvents() from brickv.mainwindow import MainWindow main_window = MainWindow() main_window.show() splash.finish(main_window) except: if '--no-error-reporter' in sys.argv: raise etype, value, tb = sys.exc_info() error = "".join(traceback.format_exception(etype, value, tb)) error = "The following error is fatal. Exiting now.\n\n" + error traceback.print_exception(etype, value, tb) try: splash.close() except: pass # Either sys.executable is /path/to/python, then run calls /path/to/python /path/to/main.py --error-report, # or sys.executable is brickv[.exe], then the --error-report flag ensures, that the path to main.py is ignored. subprocess.run([sys.executable, os.path.realpath(__file__), "--error-report"] + argv, input=error, universal_newlines=True) sys.exit(1) sys.exit(brick_viewer.exec_())
parser = argparse.ArgumentParser(\ description='Test script for tiled graphicview widget') parser.add_argument('--file', '-f', help='hdf file to load', default=None) args = parser.parse_args() if args.file is not None and not os.path.isfile(args.file): raise SystemExit("File does not exist!") app = QApplication(sys.argv) # windows always sucks!! if sys.platform.startswith("win"): sqldrivers = join(dirname(QtGui.__file__), "plugins") app.addLibraryPath(sqldrivers) splash_pix = QPixmap(':annotationtool_about.png') splash = QSplashScreen(splash_pix, Qt.WindowStaysOnTopHint) splash.setMask(splash_pix.mask()) splash.show() splash.showMessage(version.information, alignment=Qt.AnchorHorizontalCenter| Qt.AnchorVerticalCenter) app.processEvents() mw = AtMainWindow(args.file) mw.show() app.thread().msleep(1000) splash.finish(mw) sys.exit(app.exec_())
sub = host.split(".") subnet = sub[0] + "." + sub[1] + "." + sub[2] array = [host, subnet] return array if __name__ == '__main__': app = QApplication(sys.argv) #--- setting darkstyle sheet on main window dark_stylesheet = qdarkstyle.load_stylesheet_pyqt5() app.setStyleSheet(dark_stylesheet) #--- splash process splash_pix = QPixmap('logo.ico') splash = QSplashScreen(splash_pix, Qt.WindowStaysOnTopHint) splash.setWindowFlags(Qt.WindowStaysOnTopHint | Qt.FramelessWindowHint) splash.setEnabled(False) progressBar = QProgressBar(splash) progressBar.setGeometry(0, splash_pix.height() - 50, splash_pix.width(), 20) splash.show() splash.showMessage( "<h1><font color='green'>Coinpaign Scanning...</font></h1>", Qt.AlignTop | Qt.AlignCenter, Qt.black) #------------------- ex = App() sys.exit(app.exec_())
class Splash(QObject, LogMixin, EventMixin): """Splash screen class""" def __init__(self, parent, msg = ""): """ Constructor of Splash screen :param parent: ui parent :param msg: initial message text """ super().__init__() self._parent = parent self.isHidden = True self._progress = 0 self._progressBar = None self.msg = msg pixmap = QtGui.QPixmap(380, 100) pixmap.fill(QtGui.QColor("darkgreen")) self._splash = QSplashScreen(pixmap) self._splash.setParent(self._parent) self.add_progressbar() def add_progressbar(self): """Add separate progress bar to splash screen""" self._progressBar = QProgressBar(self._splash) self._progressBar.setGeometry(self._splash.width() / 10, 8 * self._splash.height() / 10, 8 * self._splash.width() / 10, self._splash.height() / 10) self._progressBar.hide() def setProgress(self, val): """ Set progress bar to ``val`` If splash has no progressbar, it will be added dynamically. Remove progressbar with ``val`` as None. :param val: absolut percent value :return: """ if val is not None: self._progressBar.show() self._progressBar.setTextVisible(True) self.progress = val try: self._progressBar.setValue(self.progress) except: pass else: self._progressBar.setTextVisible(False) self._progressBar.hide() self._progressBar.reset() if self.isHidden is True: self.isHidden = False self.show_() def incProgress(self, val): """ Increase progressbar value by ``val`` If splash has no progressbar, it will be added dynamically. Remove progressbar with ``val`` as None. :param val: value to increase by :return: """ if val is not None: self._progressBar.show() self._progressBar.setTextVisible(True) self.progress = self.progress + val try: self._progressBar.setValue(self.progress) qApp.processEvents() except: pass else: self._progressBar.setTextVisible(False) self._progressBar.hide() self._progressBar.reset() if self.isHidden is True: self.isHidden = False self.show_() def setParent(self, parent): """Set splash's parent""" self._parent = parent self._splash.setParent(parent) @pyqtSlot() @pyqtSlot(bool) def close(self, dummy = True): self.logger.debug("Hide splash") self.isHidden = True self._progressBar.hide() self._progressBar.reset() self._splash.close() @pyqtSlot() @pyqtSlot(str) def show_(self, msg = ""): if msg != "": self._splash.showMessage(msg, QtCore.Qt.AlignCenter, QtCore.Qt.white) else: self.logger.debug("Show splash, parent: " + str(self._parent)) self._splash.showMessage(self.msg, QtCore.Qt.AlignCenter, QtCore.Qt.white) try: #if platform.system() == "Linux": parentUi = self._parent.centralwidget.geometry() # need to use centralwidget for linux preferably, don't know why except: #else: parentUi = self._parent.childrenRect() mysize = self._splash.geometry() hpos = parentUi.x() + ((parentUi.width() - mysize.width()) / 2) vpos = parentUi.y() + ((parentUi.height() - mysize.height()) / 2) self._splash.move(hpos, vpos) self._splash.show() qApp.processEvents() @property def progress(self): return self._progress @progress.setter def progress(self, value): # create new exception handling vor properties # if (value != "True") and (value != "False"): # raise ValueError("describe exception") if value > 100: value = 0 if value < 0: value = 0 self._progress = value
class Example(QMainWindow, Ui_MainWindow): DEBUG = True # Если TRUE, то выводим вспомогательную информацию в консоль result = {} # Variable for JSON photo_avg = [] # Сюда помещаются картинки приблизительно равные размеру, заданному в переменной photo_size photo_date = [] # Сюда помещаются даты, когда были выложены картинки photo_max = [] # Сюда помещаются самые большие картинки current_page = 1 # Текущая страница просмоторщика label = {} # Массив элементов label loading_image = [] # Сюда помещаем список загруженных фото button = {} # Массив кнопок icon = {} # Массив иконок для button pic_date = {} # Массив времени публикации для картинок prev_mode = 0 # Флаг где находимся. 0 - если в превиюхах. 1 - если в режима просмотра большой картинки group_id = 0 # ID группы, которую будем загружать dict_count = {} # Переменная через которую сопоставляется выделенный элемент в listWidget и ID для загрузки first_run = 0 # Если приложение запустилось первый раз, то при нажатии Load загрузить аватарки групп loading_error = False # Флаг удачной загрузки def __init__(self, MainWindow): super().__init__() # Сконфигурировать интерфейс методом из базового класса MainWindow self.setupUi(MainWindow) # Показываем заставку при загрузке self.downloading('Interface is initialized...') self.wait() # Подключить созданные нами слоты к виджетам self.connect_slots() try: fp = open("settings.json", "r") try: self.settings = json.load(fp) finally: fp.close() # Количество загружаемых страниц self.num_pages = self.settings['settings']['pages_load'][0]['num_pages'] # Количество строк self.num_line = self.settings['settings']['preview'][0]['num_line'] # Количество столбцов self.num_column = self.settings['settings']['preview'][0]['num_column'] # Размер preview self.photo_size = self.settings['settings']['preview'][0]['prev_size'] # Путь (каталог на диске) для сохранения изображений self.pic_save_path = self.settings['settings']['pic_save'][0]['path'] # Прокси self.proxy_host = self.settings['settings']['proxies'][0]['host'] self.proxy_port = self.settings['settings']['proxies'][0]['port'] self.proxy_username = self.settings['settings']['proxies'][0]['username'] self.proxy_password = self.settings['settings']['proxies'][0]['password'] if not self.proxy_host: self.proxies = {} self.auth = HTTPProxyAuth('', '') if self.proxy_host and self.proxy_port: self.proxies = {"http": "http://" + self.proxy_host + ":" + self.proxy_port, "https": "https://" + self.proxy_host + ":" + self.proxy_port} self.auth = HTTPProxyAuth('', '') if self.proxy_host and self.proxy_port and self.proxy_username and self.proxy_password: self.proxies = {"http": "http://" + self.proxy_username + ':' + self.proxy_password + '@' + self.proxy_host + ':' + self.proxy_port, "https": "https://" + self.proxy_username + ':' + self.proxy_password + '@' + self.proxy_host + ':' + self.proxy_port,} self.auth = HTTPProxyAuth(self.proxy_username, self.proxy_password) if self.DEBUG: print('Proxy: ' + str(self.proxies)) # Заполняем listVidget группами без аватарки self.group_fill() except IOError: self.statusbar.showMessage('settings.json not found!') self.num_pages = 2 self.num_line = 2 self.num_column = 2 self.photo_size = 50 # self.modalWindowDownloading.close() self.splash.close() # Подключаем слоты к виджетам def connect_slots(self): self.actionLoad.triggered.connect(self.load_pic) self.actionNext.triggered.connect(self.next_pic) self.actionPreview.triggered.connect(self.preview_pic) self.actionRefresh.triggered.connect(self.refresh) self.actionSettings.triggered.connect(self.settings_window) self.actionQuit.triggered.connect(qApp.quit) self.actionAbout.triggered.connect(self.about_vk) self.actionAbout_Qt.triggered.connect(self.about_qt) self.actionHelp.triggered.connect(self.help) self.actionOpen_saving_folder.triggered.connect(self.open_saving_folder) QMainWindow.resizeEvent = self.scale_pic # Заполняем listWidget списком групп def group_fill(self): self.listWidgetMain.clear() # Очищаем listWidgetMain try: fp = open("settings.json", "r") try: self.settings = json.load(fp) finally: fp.close() except IOError: self.statusbar.showMessage('settings.json not found!') # Заполняем listWidget списком групп self.dict = self.settings['vk_groups'] # print('DICT: ' + str(self.dict)) n = 0 self.dict_count = {} # Обнуляем for i in self.dict: self.listWidgetMain.addItem(self.dict[i]) self.dict_count[n] = str(i) n += 1 # Заполняем listWidget аватарками def group_fill_ava(self): self.listWidgetMain.clear() # Очищаем listWidgetMain # Формируем список групп для которых нужно загрузить аватарку и выполняем запрос text = '' for i in range(len(self.dict_count)): text = text + str(self.dict_count[i]) if i < len(self.dict_count) - 1: text = text + ',' # Загружаем, парсим JSON и вытаскиваем аватарки групп url_ava = 'https://api.vk.com/method/groups.getById?v=5.32&group_ids=' + text if self.DEBUG: print('Get JSON Avatars URL: ' + url_ava) self.splash.showMessage('Downloading Avatars', QtCore.Qt.AlignTop | QtCore.Qt.AlignCenter, QtCore.Qt.black) try: response = requests.get(url_ava, proxies=self.proxies, auth=self.auth) except IOError: if self.DEBUG: print('ERROR Loading avatars!') self.group_fill() self.loading_error = True self.splash.close() if self.loading_error == False: result = json.loads(response.text) # Заполняем listWidget аватарками групп loading_ava = [] for i in range(len(self.dict_count)): if self.DEBUG: print(str(i) + ')' + result['response'][i]['photo_50']) self.splash.showMessage(os.path.basename(result['response'][i]['photo_50']), QtCore.Qt.AlignTop | QtCore.Qt.AlignCenter, QtCore.Qt.black) response = requests.get(result['response'][i]['photo_50'], proxies=self.proxies, auth=self.auth) image = QImage() image.loadFromData(response.content) loading_ava.append(image) item = QtWidgets.QListWidgetItem() icon = QtGui.QIcon() icon.addPixmap(QtGui.QPixmap(image), QtGui.QIcon.Normal, QtGui.QIcon.Off) item.setIcon(icon) self.listWidgetMain.addItem(item) # Заполняем listWidget названиями групп n = 0 for i in self.dict: item = self.listWidgetMain.item(n) item.setText(self.dict[i]) # item.setText(str(i) + ':' + self.dict[i]) # self.listWidgetMain.addItem(str(i) + ':' + self.dict[i]) n += 1 # Открываем каталок загрузок в текущем проводнике def open_saving_folder(self): if platform.system() == 'Linux': try: subprocess.check_call(['xdg-open', self.pic_save_path]) except subprocess.CalledProcessError: QMessageBox.critical(window, 'Error','Unable to open dir\n"File->Settings->Path"') # Помощь def help(self): print(self.dict_count) # # self.group_id = self.dict_count[self.listWidgetMain.currentRow()] # print(self.group_id) # # self.downloading() # Увеличение картинки при растяжении окна def scale_pic(self, e): if self.prev_mode == 1: self.big_check() self.label.setPixmap(QtGui.QPixmap(self.image).scaled( self.width_my, self.height_my, QtCore.Qt.KeepAspectRatio)) # Указываем путь для сохранения картинок def tool_button(self, e): print('tool button') fname = QFileDialog.getExistingDirectory(self, 'Dir', self.pic_save_path) if fname: self.lineEdit.setText(fname) # Обновить картинку def refresh(self): print('refresh') # self.load_big() self.big_check() self.label.setPixmap(QtGui.QPixmap(self.image).scaled(self.width_my, self.height_my, QtCore.Qt.KeepAspectRatio)) # self.label.mousePressEvent = self.close_full_pic_view self.actionRefresh.setEnabled(True) def about_vk(self): QMessageBox.about(window, 'About VK Girls', 'VK Girls v.1.0') def about_qt(self): QMessageBox.aboutQt(window) # Загружаем картинки при нажатии кнопки Load def load_pic(self): # Проверяем есть ли и-нет соединение try: requests.get('http://vk.com', proxies=self.proxies, auth=self.auth) except IOError: if self.DEBUG: print('Check internet connection') msgBox = QMessageBox( QMessageBox.Critical, 'Error', 'Check internet connection', QMessageBox.NoButton) msgBox.exec_() else: print('Поехали') self.current_page = 1 self.load_pic_list() self.load_pic_prev() self.draw_pic() self.check_buttons() self.statusbar.showMessage('Page: ' + str(self.current_page)) self.loading_error = False # Загружаем следующую картинку при нажатии кнопки Next def next_pic(self): # Если находимся в режиме preview, то загружаем следующие if self.prev_mode == 0: # Показываем заставку при загрузке self.downloading('Loading next pics...') self.wait() self.current_page += 1 self.load_pic_prev() self.draw_pic() self.check_buttons() self.statusbar.showMessage('Page: ' + str(self.current_page)) self.splash.close() # Если находимся в режима просмотра большой картинки, то показываем следующую else: print('--->') if self.photo_max_id < len(self.photo_max) - 1: self.photo_max_id += 1 self.load_big() self.big_check() self.label.setPixmap(QtGui.QPixmap(self.image).scaled( self.width_my, self.height_my, QtCore.Qt.KeepAspectRatio)) # Если фото последнее и режим просмотра большого фото,то делаем кнопку next в меню и на панели неактивной if self.photo_max_id >= len(self.photo_max) - 1 and self.prev_mode == 1: self.actionNext.setEnabled(False) else: self.actionNext.setEnabled(True) # Если фото первое и режим просмотра большого фото,то делаем кнопку preview неактивной if self.photo_max_id <= 0 and self.prev_mode == 1: self.actionPreview.setEnabled(False) else: self.actionPreview.setEnabled(True) # Загружаем предыдущую картинку при нажатии кнопки Preview def preview_pic(self): if self.prev_mode == 0: # Показываем заставку при загрузке self.downloading('Loading prev pics...') self.wait() self.current_page -= 1 self.load_pic_prev() self.draw_pic() self.check_buttons() self.statusbar.showMessage('Page: ' + str(self.current_page)) self.splash.close() else: print('<---') if self.photo_max_id > 0: self.photo_max_id -= 1 self.load_big() self.big_check() # Сравниваем его размер с размером окна self.label.setPixmap(QtGui.QPixmap(self.image).scaled( self.width_my, self.height_my, QtCore.Qt.KeepAspectRatio)) # Если фото последнее и режим просмотра большого фото,то делаем кнопку next в меню и на панели неактивной if self.photo_max_id >= len(self.photo_max) - 1 and self.prev_mode == 1: self.actionNext.setEnabled(False) else: self.actionNext.setEnabled(True) # Если фото первое и режим просмотра большого фото,то делаем кнопку preview неактивной if self.photo_max_id <= 0 and self.prev_mode == 1: self.actionPreview.setEnabled(False) else: self.actionPreview.setEnabled(True) # Просмотр большого фото def full_pic_view(self, event): # Показываем заставку при загрузке self.downloading('Loading full image...') self.wait() """Загрузка и просмотр большого изображения""" self.prev_mode = 1 # Выставляем флаг, что мы перешли в режим просмотра большого фото self.wat_is_button() # Какая кнопка с preview была нажата, чтобы загрузить большое фото self.clear_screen() # Удаляем все кнопки с изображениями (очищаем окно) self.check_buttons() # Проверяем флаги кнопок в меню и тулбаре # self.win_size() # Определяем текущий размер окна # Ищем большое фото mult_num = self.num_line * self.num_column self.photo_max_id = self.current_page *\ mult_num - mult_num + self.sender1 # Создаем Label в котором будем выводить фото self.label = QtWidgets.QLabel(self.centralwidget) self.label.setAlignment(QtCore.Qt.AlignCenter) self.label.setObjectName("label") self.load_big() # Загружаем большое фото self.big_check() # Сравниваем его размер с размером окна self.label.setPixmap(QtGui.QPixmap(self.image).scaled( self.width_my, self.height_my, QtCore.Qt.KeepAspectRatio)) self.gridLayout_2.addWidget(self.label, 0, 0, 0, 0) self.label.mousePressEvent = self.close_full_pic_view # Если фото последнее, то делаем кнопку next в меню и на панели неактивной if self.photo_max_id >= len(self.photo_max) - 1: self.actionNext.setEnabled(False) # Если фото первое, то делаем кнопку preview неактивной if self.photo_max_id == 0: self.actionPreview.setEnabled(False) # Закрываем заставку self.splash.close() # Загрузка большого фото def load_big(self): """Загружаем большое фото""" # req = Request(self.photo_max[self.photo_max_id]) # response = urlopen(req).read() # # Показываем заставку при загрузке # self.downloading() # self.wait() response = requests.get(self.photo_max[self.photo_max_id], proxies=self.proxies, auth=self.auth) self.image = QImage() self.image.loadFromData(response.content) # self.modalWindowDownloading.close() # Подгоняем размер картинки под размер окна def big_check(self): # Определяем размер окна, чтобы оно не растягивалось, если размер изображения больше, чем размер окна self.win_size() # Сверяем размер большого фото с размером окна if self.image.width() < self.width: self.width_my = self.image.width() self.height_my = self.image.height() else: if self.DEBUG: print('BIG_width') self.width_my = self.width - self.width * 0.1 self.height_my = self.height - self.height * 0.1 if self.height_my < self.height: if self.DEBUG: print('do nothing') else: if self.DEBUG: print('BIG_height') self.width_my = self.width - self.width * 0.1 self.height_my = self.height - self.height * 0.1 if self.DEBUG: print('Ширина:{0}; Высота:{1}'.format(self.width_my, self.height_my)) # ##############Окно настроек ###################################################### def settings_window(self): """Окно настройки""" combo = { 50: 0, 100: 1, 130: 2, 160: 3, 200: 4, 250: 5 } self.modalWindow = QWidget(window, Qt.Window) self.modalWindow.setWindowModality(Qt.WindowModal) # SettingsWindow(modalWindow) Ui_Form.setupUi(self, self.modalWindow) Ui_Form.retranslateUi(self, self.modalWindow) self.pushButtonOK.mousePressEvent = self.button_ok self.pushButtonCancel.mousePressEvent = self.button_cancel self.toolButton.mousePressEvent = self.tool_button self.pushButtonAdd.mousePressEvent = self.button_add self.pushButtonDel.mousePressEvent = self.button_del self.checkBox.stateChanged.connect(self.check_box) self.radioButtonYes.toggled.connect(self.radio_button) self.modalWindow.setAttribute(Qt.WA_DeleteOnClose, True) # modalWindow.move(window.geometry().center() - modalWindow.rect().center() - QtCore.QPoint(4, 30)) try: fp = open("settings.json", "r") try: self.settings = json.load(fp) finally: fp.close() # Размер preview self.photo_size = self.settings['settings']['preview'][0]['prev_size'] self.comboBox.setCurrentIndex(combo[self.photo_size]) # Количество загружаемых страниц self.num_pages = self.settings['settings']['pages_load'][0]['num_pages'] self.spinPages.setProperty("value", self.num_pages) # Количество строк self.num_line = self.settings['settings']['preview'][0]['num_line'] self.spinRow.setProperty("value", self.num_line) # Количество столбцов self.num_column = self.settings['settings']['preview'][0]['num_column'] self.spinColumns.setProperty("value", self.num_column) # Путь (каталог на диске) для сохранения изображений self.pic_save_path = self.settings['settings']['pic_save'][0]['path'] self.lineEdit.setText(self.pic_save_path) # Заполняем listWidget списком групп dict = self.settings['vk_groups'] for i in dict: self.listWidget.addItem(str(i) + ':' + dict[i]) # Заполняем прокси, если есть self.proxy_host = self.settings['settings']['proxies'][0]['host'] self.proxy_port = self.settings['settings']['proxies'][0]['port'] self.proxy_username = self.settings['settings']['proxies'][0]['username'] self.proxy_password = self.settings['settings']['proxies'][0]['password'] if self.proxy_host and self.proxy_port: self.radioButtonYes.setChecked(True) self.lineEditProxy.setText(self.proxy_host) self.spinBoxPort.setProperty("value", self.proxy_port) if self.proxy_username and self.proxy_password: self.checkBox.setChecked(True) self.lineEditLogin.setText(self.proxy_username) self.lineEditPwd.setText(self.proxy_password) else: self.lineEditLogin.setDisabled(True) self.lineEditPwd.setDisabled(True) else: self.radioButtonNo.setChecked(True) self.lineEditProxy.setDisabled(True) self.spinBoxPort.setDisabled(True) self.lineEditLogin.setDisabled(True) self.lineEditPwd.setDisabled(True) self.checkBox.setDisabled(True) except IOError: self.num_pages = 2 self.num_line = 2 self.num_column = 2 self.photo_size = 50 self.modalWindow.show() def radio_button(self): if self.radioButtonYes.isChecked(): self.lineEditProxy.setDisabled(False) self.spinBoxPort.setDisabled(False) self.checkBox.setDisabled(False) else: self.lineEditProxy.setDisabled(True) self.spinBoxPort.setDisabled(True) self.checkBox.setDisabled(True) self.lineEditLogin.setDisabled(True) self.lineEditPwd.setDisabled(True) self.checkBox.setChecked(False) def check_box(self): if self.checkBox.isChecked(): self.lineEditLogin.setDisabled(False) self.lineEditPwd.setDisabled(False) else: self.lineEditLogin.setDisabled(True) self.lineEditPwd.setDisabled(True) # Кнопка добавления группы в список listWidget def button_add(self, e): print('button add') self.modalWindowAdd = QWidget(window, Qt.Window) self.modalWindowAdd.setWindowModality(Qt.WindowModal) Ui_FormUrl.setupUi(self, self.modalWindowAdd) Ui_FormUrl.retranslateUi(self, self.modalWindowAdd) self.pushButtonUrl.mousePressEvent = self.buttonUrl self.modalWindowAdd.show() # Кнопка удаления группы из списка listWidget def button_del(self, e): print(self.settings['vk_groups']) # Берем из listWidget текущее значение (id группы) self.group_id = self.dict_count[self.listWidget.currentRow()] # print(self.group_id) # print(self.dict_count) # self.dict_count.pop(self.dict_count[self.group_id]) # print(self.dict_count) # Удаляем текущее значение из JSON self.settings['vk_groups'].pop(self.group_id) print(self.settings['vk_groups']) # Удаляем текущее значение из списка listWidget for item in self.listWidget.selectedItems(): self.listWidget.takeItem(self.listWidget.row(item)) def buttonUrl(self, e): url = self.lineEditUrl.text() try: response = requests.post(url, proxies=self.proxies, auth=self.auth) except IOError: print('Unable to fetch URL!') QMessageBox.critical(self.modalWindowAdd, 'Error','Unable to fetch URL!\nURL must be like: http://vk.com/sergeqwe') return None if response.status_code == 200: # Ищем ID группы result = response.text start = result.find('[group]') id = result[start:start+20] if id: id = int(sub("\D", "", id)) print(id) # Ищем название группы start = result.find('<title>') end = result.find('</title>') groupe_name = result[start+7:end] print(groupe_name) self.listWidget.addItem(str(id) + ':' + groupe_name) self.settings['vk_groups'][str(id)] = groupe_name print(self.settings['vk_groups']) else: QMessageBox.critical(self.modalWindowAdd, 'Error', 'Not a group!') return None else: print('Unable to fetch URL...') self.modalWindowAdd.close() def button_ok(self, e): # Размер preview self.settings['settings']['preview'][0]['prev_size'] = int(self.comboBox.currentText()) self.photo_size = int(self.comboBox.currentText()) # Количество загружаемых страниц self.settings['settings']['pages_load'][0]['num_pages'] = int(self.spinPages.text()) self.num_pages = int(self.spinPages.text()) # Количество строк self.settings['settings']['preview'][0]['num_line'] = int(self.spinRow.text()) self.num_line = int(self.spinRow.text()) # Количество столбцов self.settings['settings']['preview'][0]['num_column'] = int(self.spinColumns.text()) self.num_column = int(self.spinColumns.text()) # Путь (каталог на диске) для сохранения изображений self.settings['settings']['pic_save'][0]['path'] = self.lineEdit.text() self.pic_save_path = self.lineEdit.text() # Проверяем включен ли в настройках прокси # Если прокси выключен, то обнуляем переменную proxies if self.radioButtonNo.isChecked(): print('proxy_disable') self.proxies = {} self.auth = HTTPProxyAuth('', '') if self.radioButtonYes.isChecked(): if self.checkBox.isChecked(): username = self.lineEditLogin.text() password = self.lineEditPwd.text() self.proxies = { "http": 'http://' + username + ':' + password + '@' + self.lineEditProxy.text() + ':' + self.spinBoxPort.text(), "https": 'http://' + username + ':' + password + '@' + self.lineEditProxy.text() + ':' + self.spinBoxPort.text(), } self.auth = self.auth = HTTPProxyAuth(username, password) self.settings['settings']['proxies'][0]['username'] = self.lineEditLogin.text() self.settings['settings']['proxies'][0]['password'] = self.lineEditPwd.text() else: self.proxies = { "http": 'http://' + self.lineEditProxy.text() + ':' + self.spinBoxPort.text(), "https": 'http://' + self.lineEditProxy.text() + ':' + self.spinBoxPort.text(), } self.settings['settings']['proxies'][0]['username'] = '' self.settings['settings']['proxies'][0]['password'] = '' self.settings['settings']['proxies'][0]['host'] = self.lineEditProxy.text() self.settings['settings']['proxies'][0]['port'] = self.spinBoxPort.text() else: self.settings['settings']['proxies'][0]['host'] = '' self.settings['settings']['proxies'][0]['port'] = '' self.settings['settings']['proxies'][0]['username'] = '' self.settings['settings']['proxies'][0]['password'] = '' try: fp = open("settings.json", "w") try: json.dump(self.settings, fp, indent=4) finally: fp.close() except IOError: print('error') self.group_fill() self.modalWindow.close() self.first_run = 0 def button_cancel(self, e): print('cancel') self.modalWindow.close() ###################################################################################### # Флаги активности кнопок def check_buttons(self): """Флаги для выставления активности(затемненности) пунктов меню и кнопок""" # Если находимся в режиме росмотра большого фото, то делаем кнопку refresh активной # А кнопку Load недоступной if self.prev_mode == 1: self.actionRefresh.setEnabled(True) self.actionLoad.setEnabled(False) else: self.actionRefresh.setEnabled(False) self.actionLoad.setEnabled(True) if self.loading_error == False: # Если в режиме preview и на последней странице, то затемняем кнопку next if self.current_page == (len(self.result["response"]["items"])) / (self.num_line * self.num_column)\ and self.prev_mode == 0: self.actionPreview.setEnabled(True) self.actionNext.setEnabled(False) else: self.actionPreview.setEnabled(True) self.actionNext.setEnabled(True) # Если в режиме preview и на первой странице, то затемняем кнопку preview if self.current_page == 1 and self.prev_mode == 0: self.actionPreview.setEnabled(False) self.actionNext.setEnabled(True) # Загружаем список фото def load_pic_list(self): self.downloading('Loading...') self.wait() if self.first_run == 0: self.group_fill_ava() self.first_run = 1 current_row = self.listWidgetMain.currentRow() # Берем из listWidget текущее значение (id группы) if self.DEBUG: print('Current row (group): ' + str(current_row)) if current_row == -1: current_row = 0 if self.DEBUG: print('Current row (group): ' + str(current_row)) self.group_id = self.dict_count[current_row] if self.DEBUG: print('Groupe ID: ' + self.group_id) """Загружаем и парсим JSON""" # self.label.setPixmap(QtGui.QPixmap("pic/avto.jpg").scaled(200, 200, QtCore.Qt.KeepAspectRatio)) req = 'https://api.vk.com/method/photos.get?v=5.32' \ '&owner_id=-{0}' \ '&album_id=wall&count={1}' \ '&rev=1&photo_sizes=1'.format(self.group_id,(self.num_line * self.num_column) * self.num_pages) if self.DEBUG: print('Loading JSON list of pics: ' + req) try: response = requests.get(req, proxies=self.proxies, auth=self.auth, timeout=3) except requests.exceptions.Timeout: print('Time out') self.loading_error = True except requests.exceptions.ProxyError: print('04 Gateway Time-out') self.loading_error = True except IOError: print('Error loading JSON') self.loading_error = True # if response.status_code != 200: # print('Косяк. Статус код') # self.loading_error = True if self.loading_error == False: self.result = json.loads(response.text) # req = Request(req) # # try: # response = urlopen(req) # # except HTTPError as e: # print('The server couldn\'t fulfill the request.') # print('Error code: ', e.code) # exit(0) # # except URLError as e: # print('We failed to reach a server.') # print('Reason: ', e.reason) # exit(0) # # self.result = json.loads(response.read().decode('utf8')) # print('JSON LOADING OK') # print(self.result) # Ищем приблизительно равные размеры фото заданные в переменной photo_size # Так же помещаем в переменную photo_date дату публикации фото if self.DEBUG: print('Всего фото загружено: ' + str(len(self.result["response"]["items"]))) if len(self.result["response"]["items"]) < (self.num_line * self.num_column) * self.num_pages: print('НЕТ СТОЛЬКО ФОТО!') exit(0) return None self.photo_avg = [] self.photo_date = [] e = 0 while e < len(self.result["response"]["items"]): i = 0 v = [] while i < len(self.result["response"]["items"][e]["sizes"]): v.append(abs(self.photo_size - self.result["response"]["items"][e]["sizes"][i]["height"])) i += 1 out = 0 generator = enumerate(v) out = [i for i,x in generator if x == min(v)] self.photo_avg.append(self.result["response"]["items"][e]["sizes"][out[0]]["src"]) self.photo_date.append(self.result["response"]["items"][e]["date"]) e += 1 # Ищем картинку с самым большим разрешением self.photo_max = [] e = 0 while e < len(self.result["response"]["items"]): i = 0 v = 0 count = 0 while i < len(self.result["response"]["items"][e]["sizes"]): if v < self.result["response"]["items"][e]["sizes"][i]["height"]: v = self.result["response"]["items"][e]["sizes"][i]["height"] count = i i += 1 self.photo_max.append(self.result["response"]["items"][e]["sizes"][count]["src"]) e += 1 if self.DEBUG: print(self.photo_max) # self.modalWindowDownloading.close() self.splash.close() # Загружаем preview def load_pic_prev(self): """Загружаем фото с сайта в зависимости от страницы и момещаем их в список loading_image""" # Показываем заставку при загрузке self.downloading('Img...') self.wait() if self.loading_error == False: if self.result and len(self.result["response"]["items"]) == (self.num_line * self.num_column) * self.num_pages: self.loading_image = [] # Обнуляем список mult_num = self.num_line * self.num_column for i in range(self.current_page * mult_num - mult_num, self.current_page * mult_num): # req = Request(self.photo_avg[i]) # response = urlopen(req).read() try: response = requests.get(self.photo_avg[i], proxies=self.proxies, auth=self.auth) except IOError: print('Не смог загрузить preview на страницу') exit(0) image = QImage() image.loadFromData(response.content) self.loading_image.append(image) if self.DEBUG: print(str(i) + ')' + self.photo_avg[i]) self.splash.showMessage(os.path.basename(self.photo_avg[i]), QtCore.Qt.AlignTop | QtCore.Qt.AlignCenter, QtCore.Qt.black) else: print('NO_RESULT') # self.modalWindowDownloading.close() # print('На странице: ' + str(self.loading_image)) if self.loading_image[0].size().width() <=0: if self.DEBUG: print('Error internet connection') # QMessageBox.critical(window, 'Error','Error internet connection') self.splash.close() msgBox = QMessageBox( QMessageBox.Critical, 'Error', 'Check internet connection', QMessageBox.NoButton) msgBox.exec_() self.first_run = 0 return None self.splash.close() # Выводим preview def draw_pic(self): if self.loading_error == False: """Выводим preview""" self.clear_screen() # Очищаем окно if len(self.result["response"]["items"]) == (self.num_line * self.num_column) * self.num_pages: t = 0 for i in range(self.num_line): for n in range(self.num_column): self.icon[t] = QtGui.QIcon() self.icon[t].addPixmap(QtGui.QPixmap(self.loading_image[t]), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.button[t] = QtWidgets.QPushButton(self.centralwidget) self.button[t].setIcon(self.icon[t]) self.button[t].setIconSize(QtCore.QSize(self.photo_size, self.photo_size)) self.button[t].setFlat(True) # self.button[t].setStyleSheet('background-color:#FFFFFF;color:#000000;') # self.button[t].setStyleSheet("font-size:40px;background-color:#333333;border: 2px solid #222222") # self.button[t].setStyleSheet("border: 1px solid #222222") self.gridLayout_2.addWidget(self.button[t], i, n, 1, 1, QtCore.Qt.AlignTop) self.button[t].setObjectName("Button: " + str(t)) self.pic_date[t] = time.strftime("%a, %d %b %Y %H:%M:%S +0000", time.localtime(self.photo_date[t])) self.button[t].setToolTip(str(self.pic_date[t])) self.button[t].clicked.connect(self.full_pic_view) t += 1 else: print('Не совпало') exit(0) # Выход из просмотра большой картинки при нажатии левой кнопки и сохранение картинки при нажатии правой кнопки def close_full_pic_view(self, e): """Закрываем просмотр большой картинки левым кликом мыши""" if e.buttons() == QtCore.Qt.LeftButton: if self.DEBUG: print('left button pressed') self.prev_mode = 0 # Флаг, что выходим из просмотра в preview self.clear_screen() # Удаляем изображение self.check_buttons() self.draw_pic() self.statusbar.showMessage('Page: ' + str(self.current_page)) # Созраняем изображение при нажатии правой кнопки мыши if e.buttons() == QtCore.Qt.RightButton: path = self.pic_save_path + '/' + os.path.basename(self.photo_max[self.photo_max_id]) print(path) self.image.save(path) if os.path.exists(path): self.statusbar.showMessage('File saved to: ' + path ) else: self.statusbar.showMessage('File is not saved. Сheck the path settings!' ) msgBox = QMessageBox( QMessageBox.Critical, 'Error', 'File is not saved. Сheck the path settings!\n<File-Settings-Path>', QMessageBox.NoButton) msgBox.exec_() # Очищаем окно def clear_screen(self): """Удаляем все кнопки с изображениями (очищаем окно)""" while self.gridLayout_2.count(): item = self.gridLayout_2.takeAt(0) item.widget().deleteLater() # Определяем какая кнопка (превиюшка) была нажата def wat_is_button(self): """Определяем какая кнопка была нажата""" sender1 = self.sender().objectName() self.sender1 = int(sub("\D", "", sender1)) print(self.sender1) # Определяем размер окна def win_size(self): """Определяем размер окна (scrollArea), чтобы оно не растягивалось, если размер изображения больше, чем размер окна""" # self.height = window.size().height() - 70 # self.width = window.size().width() - 10 self.height = self.scrollArea.size().height() self.width = self.scrollArea.size().width() # Окно загрузки def downloading(self, msg): # print('downloading...') # self.modalWindowDownloading = QWidget(window, Qt.Window) # self.modalWindowDownloading.setWindowModality(Qt.WindowModal) # Ui_FormDownload.setupUi(self, self.modalWindowDownloading) # Ui_FormDownload.retranslateUi(self, self.modalWindowDownloading) # self.modalWindowDownloading.show() image = QPixmap('./pic/loading1.jpg') self.splash = QSplashScreen(image) self.splash.setAttribute(QtCore.Qt.WA_DeleteOnClose) self.splash = QSplashScreen(image, Qt.WindowStaysOnTopHint) self.splash.setMask(image.mask()) font = QFont(self.splash.font()) font.setPointSize(font.pointSize() + 3) self.splash.setFont(font) self.splash.showMessage(msg, QtCore.Qt.AlignTop | QtCore.Qt.AlignCenter, QtCore.Qt.black) self.splash.show() def wait(self): start = time.time() while time.time() - start < 1: time.sleep(0.001) app.processEvents()
class GuiApplicationBase(ApplicationBase, QApplication): _logger = logging.getLogger(__name__) has_gui = True ############################################## def __init__(self, args, **kwargs): super(GuiApplicationBase, self).__init__(args=args, **kwargs) # Fixme: Why ? self._logger.debug("QApplication " + str(sys.argv)) QApplication.__init__(self, sys.argv) self._logger.debug('GuiApplicationBase ' + str(args) + ' ' + str(kwargs)) self.setAttribute(Qt.AA_EnableHighDpiScaling) # from . import BabelRessource rcc_path = ConfigInstall.Path.join_share_directory('babel.rcc') self._logger.debug('Load ressource {}'.format(rcc_path)) if not QResource.registerResource(str(rcc_path)): self._logger.debug('Failed to load ressource {}'.format(rcc_path)) # self._display_splash_screen() self._main_window = None self._initialise_qml_engine() self._init_actions() ############################################## @property def main_window(self): return self._main_window @property def qml_engine(self): return self._qml_engine @property def qml_context(self): return self._qml_engine.rootContext() ############################################## def _exception_hook(self, exception_type, exception_value, exception_traceback): traceback.print_exception(exception_type, exception_value, exception_traceback) dialog = CriticalErrorDialog( exception_type, exception_value, exception_traceback, qml_engine=self._qml_engine ) rc = dialog.exec_() if rc == -1: self.exit() # return sys.__excepthook__(exception_type, exception_value, exception_traceback) ############################################## def _display_splash_screen(self): pixmap = QPixmap(':/splash screen/images/splash_screen.png') self._splash = QSplashScreen(pixmap) self._splash.show() self._splash.showMessage('<h2>Babel %(version)s</h2>' % {'version':str(Version.babel)}) self.processEvents() ############################################## def _initialise_qml_engine(self): self._qml_engine = QQmlEngine(self) qml_path = str(ConfigInstall.Path.qml_path) self._qml_engine.addImportPath(qml_path) context = self.qml_context self._application_style = ApplicationStyle() context.setContextProperty('application_style', self._application_style) self._icon_provider = IconProvider() self._qml_engine.addImageProvider('icon_provider', self._icon_provider) ############################################## def _init_actions(self): self.about_action = QAction( 'About Babel', self, triggered=self.about, ) self.exit_action = QAction( 'Exit', self, triggered=self.exit, ) self.help_action = QAction( 'Help', self, triggered=self.open_help, ) self.show_system_information_action = QAction( 'System Information', self, triggered=self.show_system_information, ) ############################################## def post_init(self): # self._splash.finish(self._main_window) # self.processEvents() # del self._splash QTimer.singleShot(0, self.execute_given_user_script) self.show_message('Welcome to Babel') # return to main and then enter to event loop ############################################## def show_message(self, message=None, echo=False, timeout=0): # Fixme: cf. PdfBrowserApplication if self._main_window is not None: self._main_window.show_message(message, echo, timeout) ############################################## # def critical_error(self, title='Babel Critical Error', message=''): # # # Fixme: CriticalErrorForm vs critical_error # # QMessageBox.critical(None, title, message) # # # Fixme: qt close? # sys.exit(1) ############################################## def open_help(self): url = QUrl() url.setScheme(DefaultConfig.Help.url_scheme) url.setHost(DefaultConfig.Help.host) url.setPath(DefaultConfig.Help.url_path_pattern) # % str(Version.babel)) QDesktopServices.openUrl(url) ############################################## def about(self): message = Messages.about_babel % {'version':str(Version.babel)} QMessageBox.about(self.main_window, 'About Babel', message) ############################################## def show_system_information(self): fields = dict(self._platform.__dict__) fields.update({ 'babel_version': str(Version.babel), }) message = Messages.system_information_message_pattern % fields QMessageBox.about(self.main_window, 'System Information', message)
from PyQt5.QtGui import QPixmap, QImage, QFont # from urllib.request import Request, urlopen # from urllib.error import URLError, HTTPError from vk_ui import Ui_MainWindow from vk_settings_ui import Ui_Form from add_ui import Ui_FormUrl from downloading_ui import Ui_FormDownload app = QApplication(sys.argv) image = QPixmap('./pic/111.jpg') splash = QSplashScreen(image) splash.setAttribute(QtCore.Qt.WA_DeleteOnClose) splash = QSplashScreen(image, Qt.WindowStaysOnTopHint) splash.setMask(image.mask()) font = QFont(splash.font()) font.setPointSize(font.pointSize() + 5) splash.setFont(font) splash.show() app.processEvents() # time.sleep(2) # splash.showMessage(splash.tr('Processing %1...{0}'),QtCore.Qt.AlignBottom | QtCore.Qt.AlignLeft, QtCore.Qt.white) # QtCore.QThread.msleep(1000) # QApplication.processEvents() for count in range(1, 6): # splash.showMessage(splash, str(count),QtCore.Qt.AlignBottom | QtCore.Qt.AlignLeft, QtCore.Qt.blue) splash.showMessage('Loading: ' + str(count), QtCore.Qt.AlignTop | QtCore.Qt.AlignLeft, QtCore.Qt.white) # print(str(count)) # app.processEvents() QtCore.QThread.msleep(1000)
def start_ide(app, filenames, projects_path, extra_plugins, linenos): """Load all the settings necessary before loading the UI, and start IDE.""" QCoreApplication.setOrganizationName('NINJA-IDE') QCoreApplication.setOrganizationDomain('NINJA-IDE') QCoreApplication.setApplicationName('NINJA-IDE') app.setWindowIcon(QIcon(":img/icon")) # Check if there is another session of ninja-ide opened # and in that case send the filenames and projects to that session running = ipc.is_running() start_server = not running[0] if running[0] and (filenames or projects_path): sended = ipc.send_data(running[1], filenames, projects_path, linenos) running[1].close() if sended: sys.exit() else: running[1].close() # Create and display the splash screen splash_pix = QPixmap(":img/splash") splash = QSplashScreen(splash_pix, Qt.WindowStaysOnTopHint) splash.setMask(splash_pix.mask()) splash.show() app.processEvents() # Set the cursor to unblinking #if not settings.IS_WINDOWS: #app.setCursorFlashTime(0) #Set the codec for strings (QString) ##QTextCodec.setCodecForCStrings(QTextCodec.codecForName('utf-8')) #Translator qsettings = ide.IDE.ninja_settings() data_qsettings = ide.IDE.data_settings() language = QLocale.system().name() lang = qsettings.value('preferences/interface/language', defaultValue=language, type='QString') + '.qm' lang_path = file_manager.create_path(resources.LANGS, lang) if file_manager.file_exists(lang_path): settings.LANGUAGE = lang_path translator = QTranslator() if settings.LANGUAGE: translator.load(settings.LANGUAGE) app.installTranslator(translator) qtTranslator = QTranslator() qtTranslator.load( "qt_" + language, QLibraryInfo.location(QLibraryInfo.TranslationsPath)) app.installTranslator(qtTranslator) #Loading Syntax splash.showMessage("Loading Syntax", Qt.AlignRight | Qt.AlignTop, Qt.black) json_manager.load_syntax() #Read Settings splash.showMessage("Loading Settings", Qt.AlignRight | Qt.AlignTop, Qt.black) #Set Stylesheet style_applied = False print(settings.NINJA_SKIN) if settings.NINJA_SKIN not in ('Default'): file_name = ("%s.qss" % settings.NINJA_SKIN) qss_file = file_manager.create_path(resources.NINJA_THEME_DOWNLOAD, file_name) if file_manager.file_exists(qss_file): with open(qss_file) as fileaccess: qss = fileaccess.read() app.setStyleSheet(qss) style_applied = True if not style_applied: if settings.NINJA_SKIN == 'Default': with open(resources.NINJA_THEME) as fileaccess: qss = fileaccess.read() app.setStyleSheet(qss) #Loading Schemes splash.showMessage("Loading Schemes", Qt.AlignRight | Qt.AlignTop, Qt.black) scheme = qsettings.value('preferences/editor/scheme', "default", type='QString') if scheme != 'default': scheme = file_manager.create_path(resources.EDITOR_SKINS, scheme + '.color') if file_manager.file_exists(scheme): resources.CUSTOM_SCHEME = json_manager.parse(open(scheme)) #Loading Shortcuts resources.load_shortcuts() #Loading GUI splash.showMessage("Loading GUI", Qt.AlignRight | Qt.AlignTop, Qt.black) ninjaide = ide.IDE(start_server) #Showing GUI ninjaide.show() #OSX workaround for ninja window not in front try: ninjaide.raise_() except: pass # I really dont mind if this fails in any form #Loading Session Files splash.showMessage("Loading Files and Projects", Qt.AlignRight | Qt.AlignTop, Qt.black) #First check if we need to load last session files if qsettings.value('preferences/general/loadFiles', True, type=bool): #Files in Main Tab files = data_qsettings.value('lastSession/openedFiles', []) tempFiles = [] if files: for file_ in files: fileData = tuple(file_) if fileData: tempFiles.append(fileData) files = tempFiles # Recent Files recent_files = data_qsettings.value('lastSession/recentFiles', []) #Current File current_file = data_qsettings.value( 'lastSession/currentFile', '', type='QString') #Projects projects = data_qsettings.value('lastSession/projects', []) else: files = [] recent_files = [] current_file = '' projects = [] #Include files received from console args file_with_nro = list([(f[0], (f[1] - 1, 0), 0) for f in zip(filenames, linenos)]) file_without_nro = list([(f, (0, 0), 0) for f in filenames[len(linenos):]]) files += file_with_nro + file_without_nro #Include projects received from console args if projects_path: projects += projects_path #FIXME: IMPROVE THIS WITH THE NEW WAY OF DO IT ninjaide.load_session_files_projects(files, projects, current_file, recent_files) #Load external plugins #if extra_plugins: #ninjaide.load_external_plugins(extra_plugins) splash.finish(ninjaide) ninjaide.notify_plugin_errors() ninjaide.show_python_detection()