コード例 #1
0
 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()
コード例 #2
0
def show_splash(version=''):
    splash_fname = utils.get_resource_path('icons/splash.jpg')
    splash_pix = QPixmap(splash_fname)

    size = splash_pix.size()*.35
    splash_pix = splash_pix.scaled(size, Qt.KeepAspectRatio,
                                   transformMode=Qt.SmoothTransformation)
    numbers = {}
    for number in list(range(10)) + ['point']:
        fname = utils.get_resource_path('icons/{}.png'.format(number))
        pix = QPixmap(fname)
        size = pix.size() * .65
        numbers[str(number)] = pix.scaled(size, Qt.KeepAspectRatio,
                                transformMode=Qt.SmoothTransformation)
    numbers['.'] = numbers['point']

    painter = QPainter(splash_pix)
    painter.begin(splash_pix)

    x, y = 470, 70
    for digit in version:
        painter.drawPixmap(x, y, numbers[digit])
        x += numbers[digit].rect().width()/3

    painter.end()

    splash = QSplashScreen(splash_pix, Qt.WindowStaysOnBottomHint)
    splash.show()
    return splash
コード例 #3
0
    def __init__(self, movie, flags, parent=None):
        movie.jumpToFrame(0)
        pixmap = QPixmap(movie.frameRect().size())

        QSplashScreen.__init__(self, pixmap, flags)
        self.movie = movie
        self.movie.frameChanged.connect(self.repaint)
コード例 #4
0
 def __init__(self):
     """
     Constructor
     """
     QSplashScreen.__init__(self, QPixmap(':/images/splash.png'),
                            Qt.WindowStaysOnTopHint)
     QApplication.flush()
コード例 #5
0
 def __init__(self, db_worker: DBWorker, parent=None):
     generate_image(get_now())
     QMainWindow.__init__(self, parent)
     self.setWindowTitle("Амбарная книга")
     self.splash_for_time = QSplashScreen(
         QtGui.QPixmap(r'images/spimage.jpg'))
     self.splash_for_time.showMessage(
         "Сохраните своё время с нами!\n\nПодключение к базе данных...\n\r"
         "\n\r\n\r", QtCore.Qt.AlignCenter | QtCore.Qt.AlignBottom,
         QtCore.Qt.black)
     self.splash_for_time.show()
     time.sleep(2)
     self.db_worker: DBWorker = db_worker
     self.con = QSqlDatabase.addDatabase("QSQLITE")
     self.con.setDatabaseName('ambar_book.db')
     self.con.open()
     self.stm: SRTM = SRTM(self)
     self.stm.setEditStrategy(QSqlTableModel.OnManualSubmit)
     generate_image(get_now())
     self.splash_for_time.setPixmap(QtGui.QPixmap(r'images/spimage.jpg'))
     self.splash_for_time.showMessage(
         "Сохраните своё время с нами!\n\nЗагрузка элементов экрана...\n\r"
         "\n\r\n\r", QtCore.Qt.AlignCenter | QtCore.Qt.AlignBottom,
         QtCore.Qt.black)
     time.sleep(2)
     self.central_widget: QWidget = QWidget(self)
     self.main_layout: QLayout = QVBoxLayout()
     self.table_labels_row: QLayout = QHBoxLayout()
     self.control_buttons_row: QLayout = QHBoxLayout()
     self.table_title_layout: QLayout = QVBoxLayout()
     self.pbcwg = QGroupBox("Выберите продукт:")
     self.pbc: QLayout = QVBoxLayout()  # ProductButtonsColumn
     self.pbcwg.setLayout(self.pbc)
     self.pbcw = QScrollArea(self)
     self.pbcw.setWidget(self.pbcwg)
     self.pbcw.setWidgetResizable(True)
     self.labels_increment_decrement_column = QVBoxLayout()
     self.product_buttons: List[ProductButton] = list()
     self.table_title: QLabel = QLabel("", parent=self)
     self.table: QTableView = QTableView(self)
     # self.table = QTableWidget(self)
     self.child_count_label = QLabel("", parent=self)
     self.date_label = QLabel(date.today().strftime("%d.%m.%Y"))
     self.add_increment_widget = AddIncrementWidget(parent=self)
     self.add_increment_widget.button.clicked.connect(self.add_increment)
     self.add_decrement_widget = AddDecrementWidget(parent=self)
     self.add_decrement_widget.button.clicked.connect(self.add_decrement)
     self.add_row_button = QPushButton("Добавить строку", parent=self)
     self.add_row_button.clicked.connect(self.add_row)
     self.delete_row_button = QPushButton("Убрать строку", parent=self)
     self.delete_row_button.clicked.connect(self.delete_row)
     self.setup_menu_bar()
     self.load_ui()
     self.setStyleSheet(css_style)
     self.chosen_product = self.product_buttons[0]
     self.chosen_product.setObjectName("chosenProductButton")
     self.table_title.setText(centralize_text(self.chosen_product.text()))
     self.load_changings()
     self.add_decrement_widget.quantity_checker.setEnabled(
         self.child_count_is_known)
コード例 #6
0
    def openDialog(self):

        # Only single instance of Plugin
        if self.exists == True: return
        else: self.exists = True

        self.resources = Resources(self.plugin_dir)
        self.dlg = PlanHeatDMMDialog(self)
        self.data = Data(plugin=False)

        splash = QSplashScreen(
            QtGui.QPixmap(self.plugin_dir + os.path.sep +
                          'resources/PlanHeatPrincipal.png'),
            QtCore.Qt.WindowStaysOnTopHint)
        splash.setWindowFlags(QtCore.Qt.WindowStaysOnTopHint
                              | QtCore.Qt.FramelessWindowHint)
        splash.setEnabled(False)
        splash.show()

        # Run the dialog event loop
        self.run()
        splash.finish(self.dlg)
        self.dlg.show()

        result = self.dlg.exec_()

        self.exists = False

        # See if OK was pressed
        if result:
            # Do something useful here
            pass
        else:
            pass
コード例 #7
0
 def __init__(self):
     QSplashScreen.__init__(self)
     text = self.outPutContents()
     self.setPixmap(QPixmap("Startup.png"))  #启动程序的图片
     self.setFont(QFont("方正细黑一简体", 11))
     self.showMessage(text, Qt.AlignHCenter | Qt.AlignVCenter,
                      QColor(240, 255, 240))
コード例 #8
0
    def __init__(self, main_window: QMainWindow):
        """
        启动动画
        """
        self.main_window = main_window

        self.splash = QSplashScreen()
コード例 #9
0
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()
コード例 #10
0
    def __init__(self):
        super().__init__()

        self.window = QtWidgets.QMainWindow()
        self.PosUi = Ui_PosWindow()
        self.LicenceUi = Ui_LicenceWindow()


        self.splash = QSplashScreen(QPixmap('pos.jpg'))

        if not (path.exists(system_path)):
            os.makedirs(system_path)
            os.makedirs(db_path)
            initDB()
            initDBTables()
            if not (path.exists(system_path + "config.INI")):
                config['DEFAULT']['user_id'] = ''  # create
                config['DEFAULT']['token'] = ''
                config['DEFAULT']['login_status'] = "False"
                status = "False"
                with open(system_path + "config.INI", "w") as configFile:
                    config.write(configFile)
        else:
            config.read(system_path + 'config.INI')
            print("Status: " + str(config['DEFAULT']['login_status']))

        self.splash.show()
        QTimer.singleShot(5000, self.navigate)
コード例 #11
0
ファイル: splashScreen.py プロジェクト: DerThorsten/ilastik
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()
コード例 #12
0
ファイル: splashScreen.py プロジェクト: lisa-simon/resipy
 def __init__(self, animation, flags):
     # run event dispatching in another thread
     QSplashScreen.__init__(self, QPixmap(), flags)
     self.movie = QMovie(animation)
     self.movie.frameChanged.connect(self.onNextFrame)
     #self.connect(self.movie, SIGNAL('frameChanged(int)'), SLOT('onNextFrame()'))
     self.movie.start()
コード例 #13
0
ファイル: main.py プロジェクト: aq1/Hospital-Helper-2
def init(bootstrap_function):
    """
    Init gui.
    Concat all files from style directory and apply stylesheet.
    Run `bootstrap_function` to prepare app.
    """
    app = QApplication(sys.argv)
    app.setWindowIcon(QIcon(os.path.join(options.STATIC_DIR, 'splash.png')))
    splash_img = QPixmap(os.path.join(options.STATIC_DIR, 'splash.png'))
    splash = QSplashScreen(splash_img)
    splash.show()
    app.processEvents()

    items = bootstrap_function()

    style = []
    style_dir = os.path.join(options.STATIC_DIR, 'style')
    for f in os.listdir(style_dir):
        if not f.endswith('.qss'):
            continue
        with open(os.path.join(style_dir, f), 'r') as qss:
            style.append(qss.read())
    app.setStyleSheet('\n'.join(style))

    mw = MainWindow(items)
    splash.finish(mw)
    sys.exit(app.exec_())
コード例 #14
0
ファイル: app.py プロジェクト: Cloudmage/mu
def run():
    """
    Creates all the top-level assets for the application, sets things up and
    then runs the application.
    """
    setup_logging()
    logging.info('Starting Mu {}'.format(__version__))
    # The app object is the application running on your computer.
    app = QApplication(sys.argv)
    # Display a friendly "splash" icon.
    splash = QSplashScreen(load_pixmap('icon'))
    splash.show()
    # Create the "window" we'll be looking at.
    editor_window = Window()
    # Create the "editor" that'll control the "window".
    editor = Editor(view=editor_window)
    # Setup the window.
    editor_window.closeEvent = editor.quit
    editor_window.setup(editor.theme)
    editor.restore_session()
    # Connect the various buttons in the window to the editor.
    button_bar = editor_window.button_bar
    button_bar.connect("new", editor.new, "Ctrl+N")
    button_bar.connect("load", editor.load, "Ctrl+O")
    button_bar.connect("save", editor.save, "Ctrl+S")
    button_bar.connect("flash", editor.flash)
    button_bar.connect("repl", editor.toggle_repl)
    button_bar.connect("zoom-in", editor.zoom_in)
    button_bar.connect("zoom-out", editor.zoom_out)
    button_bar.connect("theme", editor.toggle_theme)
    button_bar.connect("quit", editor.quit)
    # Finished starting up the application, so hide the splash icon.
    splash.finish(editor_window)
    # Stop the program after the application finishes executing.
    sys.exit(app.exec_())
コード例 #15
0
    def __init__(self, irises, settings, parent=None, chan=None, **kwargs):
        QMainWindow.__init__(self, parent)
        self._splash = QSplashScreen(self, QPixmap('data/logo.tif'))
        self._splash.show()
        self.setAttribute(Qt.WA_DeleteOnClose)
        self.setWindowTitle("CBRS Array Monitor")
        self.setMinimumSize(800, 600)
        self._settings = settings

        self.addDockWidget(
            Qt.TopDockWidgetArea,
            TopLevelControlPanel(irises=irises, settings=settings,
                                 parent=self))

        #start the window
        self.setCentralWidget(
            MainStatusWindow(irises=irises, parent=self, chan=chan))

        #load previous settings
        print("Loading %s" % self._settings.fileName())
        if self._settings.contains("MainWindow/geometry"):
            self.restoreGeometry(self._settings.value("MainWindow/geometry"))
        if self._settings.contains("MainWindow/state"):
            self.restoreState(self._settings.value("MainWindow/state"))

        #load complete
        self._splash.finish(self)
コード例 #16
0
ファイル: PyPreviewer.py プロジェクト: louisraccoon/PyStudy
 def start_logo(self):
     img_logo = QPixmap('pystudylogo.png')
     self.splash = QSplashScreen(img_logo, Qt.WindowStaysOnTopHint)
     self.splash.setMask(img_logo.mask())
     self.splash.show()
     time.sleep(1.8)
     self.splash.close()
コード例 #17
0
class MainWindow(QMainWindow):
    def __init__(self, settings, parent=None, **kwargs):
        QMainWindow.__init__(self, parent)
        self._splash = QSplashScreen(self, QPixmap('data/logo.tif'))
        self._splash.show()
        self.setAttribute(Qt.WA_DeleteOnClose)
        self.setWindowTitle("Iris Snooper GUI - %s" %
                            kwargs['handle']['label'])
        self.setMinimumSize(800, 600)
        self._settings = settings

        #load previous settings
        print("Loading %s" % self._settings.fileName())
        if self._settings.contains("MainWindow/geometry"):
            self.restoreGeometry(self._settings.value("MainWindow/geometry"))
        if self._settings.contains("MainWindow/state"):
            self.restoreState(self._settings.value("MainWindow/state"))

        #start the window
        self._plotters = PlotterWidgets(parent=self, **kwargs)
        self.setCentralWidget(self._plotters)

        #load complete
        self._splash.finish(self)

    def closeEvent(self, event):

        #stash settings
        self._settings.setValue("MainWindow/geometry", self.saveGeometry())
        self._settings.setValue("MainWindow/state", self.saveState())

        self._plotters.closeEvent(event)
コード例 #18
0
ファイル: SplashScreen.py プロジェクト: ProfDJRead/RepTate
 def clearMessage(self):
     """[summary]
     
     [description]
     """
     QSplashScreen.clearMessage(self)
     QApplication.processEvents()
コード例 #19
0
ファイル: __main__.py プロジェクト: dpgeorge/puppy
def main():
    # The app object is the application running on your computer.
    app = QApplication(sys.argv)
    app.setStyleSheet(load_stylesheet('puppy.css'))

    # A splash screen is a logo that appears when you start up the application.
    # The image to be "splashed" on your screen is in the resources/images
    # directory.
    splash = QSplashScreen(load_pixmap('splash'))
    # Show the splash.
    splash.show()

    # Make the editor with the Puppy class defined above.
    the_editor = Puppy()

    proj_root = os.path.join(ROOT, 'hello_world')
    proj = HelloWorld(proj_root, {})
    if not os.path.isdir(proj_root):
        proj.init_files()
    the_editor.add_project(proj)

    the_editor.show()
    the_editor.autosize_window()

    # Remove the splash when the_editor has finished setting itself up.
    splash.finish(the_editor)

    # Stop the program after application finishes executing.
    sys.exit(app.exec_())
コード例 #20
0
def run():
    """
    Creates all the top-level assets for the application, sets things up and
    then runs the application.
    """
    setup_logging()
    logging.info('\n\n-----------------\n\nStarting Mu {}'.format(__version__))
    logging.info(platform.uname())
    # The app object is the application running on your computer.
    app = QApplication(sys.argv)
    # Create the "window" we'll be looking at.
    editor_window = Window()
    # Create the "editor" that'll control the "window".
    editor = Editor(view=editor_window)
    editor.setup(setup_modes(editor, editor_window))
    # Setup the window.
    editor_window.closeEvent = editor.quit
    editor_window.setup(editor.debug_toggle_breakpoint, editor.theme)
    # capture the filename passed by the os, if there was one
    passed_filename = sys.argv[1] if len(sys.argv) > 1 else None
    editor.restore_session(passed_filename)
    # Connect the various UI elements in the window to the editor.
    status_bar = editor_window.status_bar
    status_bar.connect_logs(editor.show_logs, 'Ctrl+Shift+D')
    status_bar.connect_mode(editor.select_mode, 'Ctrl+Shift+M')
    # Display a friendly "splash" icon.
    splash = QSplashScreen(load_pixmap('splash-screen'))
    splash.show()
    # Finished starting up the application, so hide the splash icon.
    splash_be_gone = QTimer()
    splash_be_gone.timeout.connect(lambda: splash.finish(editor_window))
    splash_be_gone.setSingleShot(True)
    splash_be_gone.start(5000)
    # Stop the program after the application finishes executing.
    sys.exit(app.exec_())
コード例 #21
0
ファイル: app.py プロジェクト: bloodearnest/mu
def run():
    """
    Creates all the top-level assets for the application, sets things up and
    then runs the application. Specific tasks include:

    - set up logging
    - create an application object
    - create an editor window and status bar
    - display a splash screen while starting
    - close the splash screen after startup timer ends
    """
    setup_logging()
    logging.info('\n\n-----------------\n\nStarting Mu {}'.format(__version__))
    logging.info(platform.uname())
    logging.info('Python path: {}'.format(sys.path))

    # The app object is the application running on your computer.
    app = QApplication(sys.argv)
    # By default PyQt uses the script name (run.py)
    app.setApplicationName('mu')
    # Set hint as to the .desktop files name
    app.setDesktopFileName('mu.codewith.editor')
    app.setApplicationVersion(__version__)
    app.setAttribute(Qt.AA_DontShowIconsInMenus)
    # Images (such as toolbar icons) aren't scaled nicely on retina/4k displays
    # unless this flag is set
    app.setAttribute(Qt.AA_UseHighDpiPixmaps)

    # Create the "window" we'll be looking at.
    editor_window = Window()
    # Make sure all windows have the Mu icon as a fallback
    app.setWindowIcon(load_icon(editor_window.icon))
    # Create the "editor" that'll control the "window".
    editor = Editor(view=editor_window)
    editor.setup(setup_modes(editor, editor_window))
    # Setup the window.
    editor_window.closeEvent = editor.quit
    editor_window.setup(editor.debug_toggle_breakpoint, editor.theme)
    # Restore the previous session along with files passed by the os
    editor.restore_session(sys.argv[1:])
    # Connect the various UI elements in the window to the editor.
    editor_window.connect_tab_rename(editor.rename_tab, 'Ctrl+Shift+S')
    editor_window.connect_find_replace(editor.find_replace, 'Ctrl+F')
    editor_window.connect_find_replace(editor.toggle_comments, 'Ctrl+K')
    status_bar = editor_window.status_bar
    status_bar.connect_logs(editor.show_admin, 'Ctrl+Shift+D')

    # Display a friendly "splash" icon.
    splash = QSplashScreen(load_pixmap('splash-screen'))
    splash.show()

    # Hide the splash icon.
    splash_be_gone = QTimer()
    splash_be_gone.timeout.connect(lambda: splash.finish(editor_window))
    splash_be_gone.setSingleShot(True)
    splash_be_gone.start(2000)

    # Stop the program after the application finishes executing.
    sys.exit(app.exec_())
コード例 #22
0
    def run(self):
        """Run method that performs all the real work"""
        try:
            # locale.setlocale(locale.LC_ALL, 'en-GB')
            # Only single instance of Plugin
            if self.exists == True:
                return
            else:
                self.exists = True

            self.dlg = PlanHeatDMMDialog(self)
            self.resources = Resources(self.plugin_dir)
            self.data = Data(plugin=True)

            # Name of project
            self.data.projectName = master_mapping_config.CURRENT_PROJECT_NAME

            # Redirection
            dmm_folder = os.path.join(master_mapping_config.CURRENT_MAPPING_DIRECTORY,
                                                    master_mapping_config.DMM_FOLDER)
            os.makedirs(dmm_folder, exist_ok=True)
            self.data.outputSaveFile = os.path.join(dmm_folder, master_mapping_config.DMM_PREFIX)


            splash = QSplashScreen(QtGui.QPixmap(self.plugin_dir + os.path.sep + 'resources/PlanHeatPrincipal.png'), QtCore.Qt.WindowStaysOnTopHint)
            splash.setWindowFlags(QtCore.Qt.WindowStaysOnTopHint | QtCore.Qt.FramelessWindowHint)
            splash.setEnabled(False)
            splash.show()

            # Run the dialog event loop
            initWindowStatus(self)
            self.resources.loadAppResources()
            initWindowbehavior(self)

            # Deserialize the module
            DMMSerializer.deserialize(self)

            splash.finish(self.dlg)

            # show the dialog
            self.dlg.show()

            # Run the dialog event loop
            result = self.dlg.exec_()

            self.exists = False

            # See if OK was pressed
            if result:
                # Do something useful here -
                pass
            else:
                pass



        except Exception as e:
            self.exists = False
            print(str(e))
コード例 #23
0
    def __init__(self, movie, parent=None):
        movie.jumpToFrame(0)
        pixmap = QPixmap(movie.frameRect().size())

        QSplashScreen.__init__(self or parent, pixmap,
                               QtCore.Qt.WindowStaysOnTopHint)
        self.movie = movie
        self.movie.frameChanged.connect(self.repaint)
コード例 #24
0
 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()
コード例 #25
0
 def __init__(self):
     QSplashScreen.__init__(self)
     self.setPixmap(QPixmap(setting.imgLogo).scaledToWidth(500))
     self.setWindowFlag(Qt.WindowStaysOnTopHint)
     self.setWindowFlag(Qt.FramelessWindowHint)
     self.mousePressEvent = self.MousePressEvent
     self.keyPressEvent = self.KeyPressEvent
     self.show()
コード例 #26
0
 def __init__(self):
     path_here = os.path.realpath(__file__)
     imfile = os.path.join(os.path.split(path_here)[0], 'loading.png')
     splash_pix = QPixmap(imfile)
     self.splash = QSplashScreen(splash_pix)  #, Qt.WindowStaysOnTopHint)
     self.splash.setMask(splash_pix.mask())
     self.splash.show()
     QApplication.processEvents()
コード例 #27
0
    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()
コード例 #28
0
 def showSplashScreen(self):
     self.pix = QPixmap("SplashPage.png")
     self.splash = QSplashScreen(self.pix, Qt.WindowStaysOnTopHint)
     # adding progress bar
     self.progressBar = QProgressBar(self.splash)
     self.progressBar.setMaximum(17)
     self.progressBar.setGeometry(0, self.pix.height() - 15, 834, 20)
     self.splash.show()
コード例 #29
0
ファイル: login.py プロジェクト: yosoyfunes/python101-2017-1c
def Ui_Bienvenida():
    splash_pix = QtGui.QPixmap('img/fondo_pantalla_de_bienvenida.png')
    splash = QSplashScreen(splash_pix, QtCore.Qt.WindowStaysOnTopHint)
    splash.show()

    def Bienvenida():
        splash.close()

    QtCore.QTimer.singleShot(500, Bienvenida)
コード例 #30
0
ファイル: splashScreen.py プロジェクト: buswedg/subdownloader
    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()
コード例 #31
0
ファイル: splashScreen.py プロジェクト: buswedg/subdownloader
 def __init__(self):
     """
     Constructor
     """
     pixmap = QPixmap(':/images/splash.png')
     self.labelAlignment = Qt.Alignment(
         Qt.AlignBottom | Qt.AlignRight | Qt.AlignAbsolute)
     QSplashScreen.__init__(self, pixmap, Qt.WindowStaysOnTopHint)
     QApplication.flush()
コード例 #32
0
ファイル: misc.py プロジェクト: HaoDrang/big-brother-bot
 def __init__(self, min_splash_time=2):
     """
     Initialize the B3 splash screen.
     :param min_splash_time: the minimum amount of seconds the splash screen should be drawn.
     """
     self.splash_pix = QPixmap(B3_SPLASH)
     self.min_splash_time = time() + min_splash_time
     QSplashScreen.__init__(self, self.splash_pix, Qt.WindowStaysOnTopHint)
     self.setMask(self.splash_pix.mask())
コード例 #33
0
    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))
コード例 #34
0
 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
コード例 #35
0
 def __init__(self):
     super(Ui_MainWindow, self).__init__()     
     splash_pix = QPixmap(':/imgs/imgs/splash.png')
     self.splash = QSplashScreen(splash_pix, QtCore.Qt.WindowStaysOnTopHint)
     self.splash.show()         
             
     self.controller = Controller(self)   
     self.progress = 0
     self.timer = QBasicTimer()        
コード例 #36
0
ファイル: SplashScreen.py プロジェクト: fizyk20/subdownloader
    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()
コード例 #37
0
ファイル: SplashScreen.py プロジェクト: fizyk20/subdownloader
 def __init__(self):
     """
     Constructor
     """
     img_path = os.path.join(os.getcwd(), 'gui', 'images', 'splash.png')
     pixmap = QPixmap(img_path)
     self.labelAlignment = Qt.Alignment(
         Qt.AlignBottom | Qt.AlignRight | Qt.AlignAbsolute)
     QSplashScreen.__init__(self, pixmap)
     self.show()
     QApplication.flush()
コード例 #38
0
ファイル: __init__.py プロジェクト: AlexSchr/frescobaldi
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)
コード例 #39
0
    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()
コード例 #40
0
ファイル: app.py プロジェクト: willingc/mu
def run():
    """
    Creates all the top-level assets for the application, sets things up and
    then runs the application. Specific tasks include:

    - set up logging
    - create an application object
    - create an editor window and status bar
    - display a splash screen while starting
    - close the splash screen after startup timer ends
    """
    setup_logging()
    logging.info('\n\n-----------------\n\nStarting Mu {}'.format(__version__))
    logging.info(platform.uname())
    logging.info('Python path: {}'.format(sys.path))

    # The app object is the application running on your computer.
    app = QApplication(sys.argv)
    app.setAttribute(Qt.AA_DontShowIconsInMenus)

    # Create the "window" we'll be looking at.
    editor_window = Window()
    # Create the "editor" that'll control the "window".
    editor = Editor(view=editor_window)
    editor.setup(setup_modes(editor, editor_window))
    # Setup the window.
    editor_window.closeEvent = editor.quit
    editor_window.setup(editor.debug_toggle_breakpoint, editor.theme)
    # Restore the previous session along with files passed by the os
    editor.restore_session(sys.argv[1:])
    # Connect the various UI elements in the window to the editor.
    editor_window.connect_tab_rename(editor.rename_tab, 'Ctrl+Shift+S')
    status_bar = editor_window.status_bar
    status_bar.connect_logs(editor.show_admin, 'Ctrl+Shift+D')

    # Display a friendly "splash" icon.
    splash = QSplashScreen(load_pixmap('splash-screen'))
    splash.show()

    # Finished starting up the application, so hide the splash icon.
    splash_be_gone = QTimer()
    splash_be_gone.timeout.connect(lambda: splash.finish(editor_window))
    splash_be_gone.setSingleShot(True)
    splash_be_gone.start(5000)

    # Stop the program after the application finishes executing.
    sys.exit(app.exec_())
コード例 #41
0
ファイル: __init__.py プロジェクト: linguistica-uchicago/lxa5
def main():
    app = QApplication(sys.argv)
    app.setStyle('cleanlooks')
    app.setApplicationName("Linguistica")

    # Get screen resolution
    # Why do we need to know screen resolution?
    # Because this information is useful for setting the size of particular
    # widgets, e.g., the webview for visualizing the word neighbor manifold
    # (the bigger the webview size, the better it is for visualization!)
    resolution = app.desktop().screenGeometry()
    screen_width = resolution.width()
    screen_height = resolution.height()

    # create and display splash screen
    splash_image_path = os.path.join(os.path.dirname(__file__),
                                     'lxa_splash_screen.png')
    splash_image = QPixmap(splash_image_path)
    splash_screen = QSplashScreen(splash_image, Qt.WindowStaysOnTopHint)
    splash_screen.setMask(splash_image.mask())
    splash_screen.show()
    app.processEvents()
    time.sleep(2)

    # launch graphical user interface
    form = MainWindow(screen_height, screen_width, __version__)
    form.show()
    splash_screen.finish(form)
    app.exec_()
コード例 #42
0
ファイル: Hitagi.py プロジェクト: gimu/hitagi-reader.py
def run(image_path = None):
    # Global exceptions
    sys.excepthook = excepthook

    app = QApplication(sys.argv) 

    # Splash screen
    splash_pix = QPixmap('resources/splash.jpg')
    splash = QSplashScreen(splash_pix)
    splash.setMask(splash_pix.mask())
    splash.show()
    
    app.processEvents()
    
    # Load translation
    locale_code = SettingsModel().get('Language', 'code')
    if locale_code != "en_US": # Standard language
        # Standard translator for the generated GUI
        translator = QTranslator()
        translator.load('localization/' + locale_code + '.qm')
        app.installTranslator(translator)

        # Translator for various GUI elements
        translator_2 = QTranslator()
        translator_2.load('localization/' + locale_code + '_2.qm')
        app.installTranslator(translator_2)

    # Start
    m = Hitagi(image_path) # Pass image path
    
    splash.finish(m)
    sys.exit(app.exec())
コード例 #43
0
ファイル: main.py プロジェクト: sergeqwe/vk
    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()
コード例 #44
0
ファイル: ChemDB.py プロジェクト: dedichan/ChemDB
    def __init__(self,parent=None):
        #splash screen initialisation
        self.splash_pix = QPixmap('data/loading.jpg')
        self.splash = QSplashScreen(self.splash_pix, QtCore.Qt.WindowStaysOnTopHint)
        self.splash.setMask(self.splash_pix.mask())
        self.splash.show()

        super(tempapp, self).__init__(parent)
        self.setupUi(self)
コード例 #45
0
    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

        self.setAttribute(Qt.AA_UseDesktopOpenGL)

        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")
コード例 #46
0
ファイル: app.py プロジェクト: alistair-broomhead/mu
def main():
    # The app object is the application running on your computer.
    app = QApplication(sys.argv)
    app.setStyleSheet(load_stylesheet('mu.css'))

    # A splash screen is a logo that appears when you start up the application.
    # The image to be "splashed" on your screen is in the resources/images
    # directory.
    splash = QSplashScreen(load_pixmap('icon'))
    splash.show()

    # Make the editor with the Mu class defined above.
    the_editor = Mu()
    the_editor.show()
    the_editor.autosize_window()

    # Remove the splash when the_editor has finished setting itself up.
    splash.finish(the_editor)

    # Stop the program after the application finishes executing.
    sys.exit(app.exec_())
コード例 #47
0
ファイル: app.py プロジェクト: lordmauve/mu
def run():
    """
    Creates all the top-level assets for the application, sets things up and
    then runs the application.
    """
    setup_logging()
    logging.info('\n\n-----------------\n\nStarting Mu {}'.format(__version__))
    logging.info(platform.uname())
    logging.info('Python path: {}'.format(sys.path))
    # The app object is the application running on your computer.
    app = QApplication(sys.argv)
    # Create the "window" we'll be looking at.
    editor_window = Window()
    # Create the "editor" that'll control the "window".
    editor = Editor(view=editor_window)
    editor.setup(setup_modes(editor, editor_window))
    # Setup the window.
    editor_window.closeEvent = editor.quit
    editor_window.setup(editor.debug_toggle_breakpoint, editor.theme)
    # capture the filename passed by the os, if there was one
    passed_filename = sys.argv[1] if len(sys.argv) > 1 else None
    editor.restore_session(passed_filename)
    # Connect the various UI elements in the window to the editor.
    editor_window.connect_tab_rename(editor.rename_tab, 'Ctrl+Shift+S')
    status_bar = editor_window.status_bar
    status_bar.connect_logs(editor.show_logs, 'Ctrl+Shift+D')
    status_bar.connect_mode(editor.select_mode, 'Ctrl+Shift+M')
    # Display a friendly "splash" icon.
    splash = QSplashScreen(load_pixmap('splash-screen'))
    splash.show()
    # Finished starting up the application, so hide the splash icon.
    splash_be_gone = QTimer()
    splash_be_gone.timeout.connect(lambda: splash.finish(editor_window))
    splash_be_gone.setSingleShot(True)
    splash_be_gone.start(5000)
    # Stop the program after the application finishes executing.
    sys.exit(app.exec_())
コード例 #48
0
ファイル: splash.py プロジェクト: pandel/opsiPackageBuilder
    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()
コード例 #49
0
ファイル: QtApplication.py プロジェクト: derekhe/Uranium
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
コード例 #50
0
ファイル: SplashScreen.py プロジェクト: fizyk20/subdownloader
 def clearMessage(self):
     """
     Public method to clear the message shown.
     """
     QSplashScreen.clearMessage(self)
     QApplication.processEvents()
コード例 #51
0
ファイル: analyzer.py プロジェクト: whmrtm/friture
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_())
コード例 #52
0
ファイル: ChemDB.py プロジェクト: dedichan/ChemDB
class tempapp(QMainWindow, tempwin):
    def __init__(self,parent=None):
        #splash screen initialisation
        self.splash_pix = QPixmap('data/loading.jpg')
        self.splash = QSplashScreen(self.splash_pix, QtCore.Qt.WindowStaysOnTopHint)
        self.splash.setMask(self.splash_pix.mask())
        self.splash.show()

        super(tempapp, self).__init__(parent)
        self.setupUi(self)
    def main(self):
        #launching program
        self.hide()
        self.launch()
    def launch(self):
        #reading configuration
        config=open('data/configure')
        config=config.readlines()
        envir=main.principal
        self.result={}
        for info in range(len(config)) :
            temp=config[info].split('=')
            temp[1]=temp[1].split('\n')[0]
            self.result[temp[0]]=temp[1]

        if self.result['db']=='' :
            #if no databatse, asking user for creating/pointing
            h=QMessageBox(parent=self, text="No DB has been pointed. \nDo you want to create a new database or to load an existing database ?")
            h.addButton(QPushButton('Close'), QMessageBox.YesRole)
            h.addButton(QPushButton('Load an Existing DB'), QMessageBox.NoRole)
            h.addButton(QPushButton('New DB'), QMessageBox.HelpRole)
            self.splash.hide()
            tot = h.exec_()
            if tot==0 :
                self.terminer()
            if tot==1 :
                self.loaddb()
            if tot==2 :
                self.newdb()
        else :
            #if already configured : checking if the DB still exist
            if os.path.exists(self.result['db'])==True :
                None
            else :
                #if db do not exist : delete configuration and reboot program
                self.splash.hide()
                h=QMessageBox(parent=self, text="Corrupted file or non existent : Deleting configuration")
                self.result['db']=""
                new_conf=''
                for i in self.result :
                    new_conf+='%s=%s\n' % (i,self.result[i])
                config=open('data/configure','w')
                config.write(new_conf)
                config.close()
                h.exec_()
                python = sys.executable
                os.execl(python, python, * sys.argv)
            #launching program if all checkpoints are ok
            self.splash.hide()
            prog=main.principal()
            prog.main()
            sys.exit(app.exec_())
    def loaddb (self) :
        #loading db file
        fname=QFileDialog.getOpenFileName(self, 'Choose a DB', '/','SQLite Databse (*.sqlite)')[0]
        if fname=='' :
            z=QMessageBox(parent=self, text="No DB has been selected, closing program")
            z.exec_()
            z.exec_()
            self.terminer()
        isvalid=cursor.verif(str(fname))
        #checking is the DB is valid
        if isvalid==False :
            z=QMessageBox(parent=self, text="Wrong File/File Corruption. \nClosing programm")
            z.exec_()
            self.terminer()
        else :
            #writiing new configuration
            self.result['db']=str(fname)
            new_conf=''
            for i in self.result :
                new_conf+='%s=%s\n' % (i,self.result[i])
            config=open('data/configure','w')
            config.write(new_conf)
            config.close()
            python = sys.executable
            os.execl(python, python, * sys.argv)
    def terminer (self) :
        #QApplication.quit()
        #sys.exit(app.exec_())
        sys.exit(0)

    def newdb (self) :
        #new db creation
        fname=QFileDialog.getSaveFileName(self, 'Create a DB', '/','SQLite Databse (*.sqlite)')[0]
        shutil.copy('data/model.sqlite',fname)
        self.result['db']=str(fname)
        new_conf=''
        for i in self.result :
            new_conf+='%s=%s\n' % (i,self.result[i])
        config=open('data/configure','w')
        config.write(new_conf)
        config.close()
        python = sys.executable
        os.execl(python, python, * sys.argv)
コード例 #53
0
ファイル: main.py プロジェクト: sergeqwe/vk
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()
コード例 #54
0
ファイル: splash.py プロジェクト: pandel/opsiPackageBuilder
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
コード例 #55
0
ファイル: analyzer.py プロジェクト: claypipkin/friture
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_())
コード例 #56
0
ファイル: CellAnnotator.py プロジェクト: manerotoni/afw
    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_())
コード例 #57
0
ファイル: main.py プロジェクト: ajoros/ves
        self.schlumbergerLayout = False
        self.wennerLayout = True


    def schlumberger(self):
        """Define Schlumberger layout is True"""
        self.schlumbergerLayout = True
        self.wennerLayout = False


if __name__ == '__main__':

    app = QApplication(sys.argv)
    app.setWindowIcon(QIcon('hand_drill.png'))

    splashPix = QPixmap('splash.png')
    splashScreen = QSplashScreen(splashPix, Qt.WindowStaysOnTopHint)

    splashScreen.setMask(splashPix.mask())
    splashScreen.show()
    app.processEvents()

    time.sleep(3)

    startup = StartupWindow(tableData, headers, colors, old_coefficients)
    startup.show()

    splashScreen.finish(startup)

    sys.exit(app.exec_())
コード例 #58
0
ファイル: test2.py プロジェクト: sergeqwe/vk
from PyQt5.QtWidgets import QApplication, QWidget, QMainWindow, QAction, qApp, QFileDialog, QMessageBox, QSplashScreen
from PyQt5 import QtGui, QtCore, QtWidgets
from PyQt5.QtCore import Qt, QCoreApplication
# from PyQt5.QtWidgets import QToolTip
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)
コード例 #59
0
ファイル: main.py プロジェクト: Tinkerforge/brickv
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_())