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_())
def main(): """Main Loop.""" APPNAME = str(__package__ or __doc__)[:99].lower().strip().replace(" ", "") try: os.nice(19) # smooth cpu priority libc = cdll.LoadLibrary('libc.so.6') # set process name buff = create_string_buffer(len(APPNAME) + 1) buff.value = bytes(APPNAME.encode("utf-8")) libc.prctl(15, byref(buff), 0, 0, 0) except Exception as reason: print(reason) app = QApplication(sys.argv) app.setApplicationName(__doc__.strip().lower()) app.setOrganizationName(__doc__.strip().lower()) app.setOrganizationDomain(__doc__.strip()) app.setWindowIcon(QIcon.fromTheme("text-x-python")) web = MainWindow() app.aboutToQuit.connect(web.process.kill) try: opts, args = getopt(sys.argv[1:], 'hv', ('version', 'help')) except: pass for o, v in opts: if o in ('-h', '--help'): print(''' Usage: -h, --help Show help informations and exit. -v, --version Show version information and exit.''') return sys.exit(1) elif o in ('-v', '--version'): print(__version__) return sys.exit(1) # web.show() # comment out to hide/show main window, normally dont needed sys.exit(app.exec_())
def __init__(self, view, model, status_bar, toolbar, navigation): """ Init :param MainWindowView view: the ui of the mainwindow component :param sakia.gui.main_window.model.MainWindowModel: the model of the mainwindow component :param sakia.gui.main_window.status_bar.controller.StatusBarController status_bar: the controller of the status bar component :param sakia.gui.main_window.toolbar.controller.ToolbarController toolbar: the controller of the toolbar component :param sakia.gui.navigation.controller.NavigationController navigation: the controller of the navigation :param PasswordAsker password_asker: the password asker of the application :type: sakia.core.app.Application """ # Set up the user interface from Designer. super().__init__() self.view = view self.model = model self.initialized = False self.status_bar = status_bar self.toolbar = toolbar self.navigation = navigation self.stacked_widgets = {} self.view.bottom_layout.insertWidget(0, self.navigation.view) self.view.top_layout.addWidget(self.toolbar.view) self.view.setStatusBar(self.status_bar.view) QApplication.setWindowIcon(QIcon(":/icons/sakia_logo"))
def main(): app = QApplication([i.encode('utf-8') for i in sys.argv]) app.setOrganizationName(ffmc.__name__) app.setOrganizationDomain(ffmc.__url__) app.setApplicationName('FF Multi Converter') app.setWindowIcon(QIcon(':/ffmulticonverter.png')) locale = QLocale.system().name() qtTranslator = QTranslator() if qtTranslator.load('qt_' + locale, ':/'): app.installTranslator(qtTranslator) appTranslator = QTranslator() if appTranslator.load('ffmulticonverter_' + locale, ':/'): app.installTranslator(appTranslator) if not os.path.exists(config.log_dir): os.makedirs(config.log_dir) logging.basicConfig( filename=config.log_file, level=logging.DEBUG, format=config.log_format, datefmt=config.log_dateformat ) converter = MainWindow() converter.show() app.exec_()
def _on_player_song_changed(self, song): song_label = self.ui.status_panel.song_label song_label.set_song(song.title + ' - ' + song.artists) self.player_img = self.set_background(song.img) if self.player_img is not None: QApplication.setWindowIcon(QIcon(self.player_img)) self.update()
def __init__(self, pubsub_gateway, player_kwargs=None): CliApp.__init__(self, pubsub_gateway, player_kwargs=player_kwargs) QWidget.__init__(self) self.request = Request(self) self.tips_manager = TipsManager(self) self.hotkey_manager = Hotkey(self) #: collections manager self.coll_mgr = CollectionManager(self) self.img_ctl = ImgController(self) self.playlists = PlaylistsModel(parent=self) self.histories = HistoriesModel(parent=self) self.providers = ProvidersModel(parent=self) self.my_music = MyMusicModel(parent=self) self.collections = CollectionsModel(parent=self) self.ui = Ui(self) self.player_pixmap = None self.show_msg = self.ui.magicbox.show_msg self.resize(1000, 618) self.setObjectName('app') QApplication.setWindowIcon(QIcon(APP_ICON)) self.bind_signal()
def main(): """Main Loop.""" APPNAME = str(__package__ or __doc__)[:99].lower().strip().replace(" ", "") if not sys.platform.startswith("win") and sys.stderr.isatty(): def add_color_emit_ansi(fn): """Add methods we need to the class.""" def new(*args): """Method overload.""" if len(args) == 2: new_args = (args[0], copy(args[1])) else: new_args = (args[0], copy(args[1]), args[2:]) if hasattr(args[0], 'baseFilename'): return fn(*args) levelno = new_args[1].levelno if levelno >= 50: color = '\x1b[31;5;7m\n ' # blinking red with black elif levelno >= 40: color = '\x1b[31m' # red elif levelno >= 30: color = '\x1b[33m' # yellow elif levelno >= 20: color = '\x1b[32m' # green elif levelno >= 10: color = '\x1b[35m' # pink else: color = '\x1b[0m' # normal try: new_args[1].msg = color + str(new_args[1].msg) + ' \x1b[0m' except Exception as reason: print(reason) # Do not use log here. return fn(*new_args) return new # all non-Windows platforms support ANSI Colors so we use them log.StreamHandler.emit = add_color_emit_ansi(log.StreamHandler.emit) log.basicConfig(level=-1, format="%(levelname)s:%(asctime)s %(message)s") log.getLogger().addHandler(log.StreamHandler(sys.stderr)) log.info(__doc__) try: os.nice(19) # smooth cpu priority libc = cdll.LoadLibrary('libc.so.6') # set process name buff = create_string_buffer(len(APPNAME) + 1) buff.value = bytes(APPNAME.encode("utf-8")) libc.prctl(15, byref(buff), 0, 0, 0) except Exception as reason: log.warning(reason) signal.signal(signal.SIGINT, signal.SIG_DFL) # CTRL+C work to quit app app = QApplication(sys.argv) app.setApplicationName(APPNAME) app.setOrganizationName(APPNAME) app.setOrganizationDomain(APPNAME) app.instance().setQuitOnLastWindowClosed(False) # no quit on dialog close icon = QIcon(app.style().standardPixmap(QStyle.SP_FileIcon)) app.setWindowIcon(icon) win = MainWindow(icon) win.show() log.info('Total Maximum RAM Memory used: ~{} MegaBytes.'.format(int( resource.getrusage(resource.RUSAGE_SELF).ru_maxrss * resource.getpagesize() / 1024 / 1024 if resource else 0))) sys.exit(app.exec_())
def main(): parser = argparse.ArgumentParser(description='A prototype of BitTorrent client (GUI)') parser.add_argument('--debug', action='store_true', help='Show debug messages') parser.add_argument('filenames', nargs='*', help='Torrent file names') args = parser.parse_args() if not args.debug: logging.disable(logging.INFO) app = QApplication(sys.argv) app.setWindowIcon(load_icon('logo')) with closing(asyncio.get_event_loop()) as loop: if loop.run_until_complete(find_another_daemon(args.filenames)): if not args.filenames: QMessageBox.critical(None, 'Failed to start', 'Another program instance is already running') return control_thread = ControlManagerThread() main_window = MainWindow(control_thread) control_thread.start() app.lastWindowClosed.connect(control_thread.stop) main_window.add_torrent_files(args.filenames) return app.exec()
def main(): app = QApplication(sys.argv) QCoreApplication.setOrganizationName('Hardcoded Software') QCoreApplication.setApplicationName(__appname__) QCoreApplication.setApplicationVersion(__version__) setupQtLogging() settings = QSettings() lang = settings.value('Language') locale_folder = op.join(BASE_PATH, 'locale') install_gettext_trans_under_qt(locale_folder, lang) # Handle OS signals setUpSignals() # Let the Python interpreter runs every 500ms to handle signals. This is # required because Python cannot handle signals while the Qt event loop is # running. from PyQt5.QtCore import QTimer timer = QTimer() timer.start(500) timer.timeout.connect(lambda: None) # Many strings are translated at import time, so this is why we only import after the translator # has been installed from qt.app import DupeGuru app.setWindowIcon(QIcon(QPixmap(":/{0}".format(DupeGuru.LOGO_NAME)))) global dgapp dgapp = DupeGuru() install_excepthook('https://github.com/hsoft/dupeguru/issues') result = app.exec() # I was getting weird crashes when quitting under Windows, and manually deleting main app # references with gc.collect() in between seems to fix the problem. del dgapp gc.collect() del app gc.collect() return result
def _on_player_song_changed(self, song): song_label = self.ui.status_panel.song_label song_label.set_song(song.title + ' - ' + song.artists_name) self.player_pixmap = self.pixmap_from_url(song.album_img) if self.player_pixmap is not None: QApplication.setWindowIcon(QIcon(self.player_pixmap)) self.update()
def __init__(self): super().__init__() self.player = Player(self) self.player_mode_manager = PlayerModeManager(self) self.request = Request(self) self.server = Server(self) self.theme_manager = ThemeManager(self) self.tips_manager = TipsManager(self) self.hotkey_manager = Hotkey(self) self.plugins_manager = PluginsManager(self) self.version_manager = VersionManager(self) self.theme_manager.set_theme(DEFAULT_THEME_NAME) self.ui = Ui(self) self._init_managers() self.player_pixmap = None self.resize(960, 600) self.setObjectName('app') QApplication.setWindowIcon(QIcon(APP_ICON)) self.set_theme_style() self.bind_signal() self.test()
def simpleAppStartup( argv, appinfo, mwFactory, quitOnLastWindowClosed=True, app=None, raiseIt=True, installErrorHandler=False ): """ Module function to start up an application that doesn't need a specialized start up. This function is used by all of eric6's helper programs. @param argv list of commandline parameters (list of strings) @param appinfo dictionary describing the application @param mwFactory factory function generating the main widget. This function must accept the following parameter. <dl> <dt>argv</dt> <dd>list of commandline parameters (list of strings)</dd> </dl> @keyparam quitOnLastWindowClosed flag indicating to quit the application, if the last window was closed (boolean) @keyparam app reference to the application object (QApplication or None) @keyparam raiseIt flag indicating to raise the generated application window (boolean) @keyparam installErrorHandler flag indicating to install an error handler dialog (boolean) @return exit result (integer) """ handleArgs(argv, appinfo) if app is None: # set the library paths for plugins setLibraryPaths() app = E5Application(argv) app.setQuitOnLastWindowClosed(quitOnLastWindowClosed) # the following code depends upon a valid application object import Preferences initializeResourceSearchPath() QApplication.setWindowIcon(UI.PixmapCache.getIcon("eric.png")) qt4TransDir = Preferences.getQt4TranslationsDir() if not qt4TransDir: qt4TransDir = QLibraryInfo.location(QLibraryInfo.TranslationsPath) loadTranslators(qt4TransDir, app) w = mwFactory(argv) if quitOnLastWindowClosed: app.lastWindowClosed.connect(app.quit) w.show() if raiseIt: w.raise_() if installErrorHandler: # generate a graphical error handler from E5Gui import E5ErrorMessage eMsg = E5ErrorMessage.qtHandler() eMsg.setMinimumSize(600, 400) return app.exec_()
def set_music_cover_img(cls, res): img = QImage() img.loadFromData(res.readAll()) pixmap = QPixmap(img) cls.ui.ALBUM_IMG_LABEL.setPixmap(pixmap.scaled(cls.ui.ALBUM_IMG_LABEL.size(), Qt.IgnoreAspectRatio, Qt.SmoothTransformation)) QApplication.setWindowIcon(QIcon(pixmap)) cls.controller.desktop_mini.content.setPixmap(pixmap)
def main(): app = QApplication(sys.argv) app.setWindowIcon(QIcon('aikon.png')) w = RMainWindow() w.show() app.exec_()
def main(): app = QApplication(sys.argv) app.setWindowIcon(QIcon('bbproject.png')) main_window = MainUI() main_window.setWindowTitle("BBFlight Client V0.0000001") main_window.show() sys.exit(app.exec_())
def main(): config_logging() app = QApplication(sys.argv) # 给应用设置一个图标 app.setWindowIcon(QIcon('Icons/main.ico')) mainForm = MainForm() mainForm.show() sys.exit(app.exec_())
def __init__(self, app): """ Init :param cutecoin.core.app.Application app: application :type: cutecoin.core.app.Application """ # Set up the user interface from Designer. super().__init__() self.setupUi(self) QApplication.setWindowIcon(QIcon(":/icons/cutecoin_logo")) self.app = app logging.debug(app.thread()) logging.debug(self.thread()) self.password_asker = None self.initialized = False self.busybar = QProgressBar(self.statusbar) self.busybar.setMinimum(0) self.busybar.setMaximum(0) self.busybar.setValue(-1) self.statusbar.addWidget(self.busybar) self.busybar.hide() self.app.version_requested.connect(self.latest_version_requested) self.app.get_last_version() self.combo_referential = QComboBox(self) self.combo_referential.setEnabled(False) self.combo_referential.currentIndexChanged.connect(self.referential_changed) self.status_label = QLabel("", self) self.status_label.setTextFormat(Qt.RichText) self.label_time = QLabel("", self) self.statusbar.addPermanentWidget(self.status_label, 1) self.statusbar.addPermanentWidget(self.label_time) self.statusbar.addPermanentWidget(self.combo_referential) self.update_time() self.loader = Loader(self.app) self.loader.loaded.connect(self.loader_finished) self.loader.connection_error.connect(self.display_error) self.homescreen = HomeScreenWidget(self.app) self.centralWidget().layout().addWidget(self.homescreen) self.homescreen.button_new.clicked.connect(self.open_add_account_dialog) self.homescreen.button_import.clicked.connect(self.import_account) self.open_ucoin_info = lambda: QDesktopServices.openUrl(QUrl("http://ucoin.io/theoretical/")) self.homescreen.button_info.clicked.connect(self.open_ucoin_info) self.import_dialog = None self.export_dialog = None # TODO: There are too much refresh() calls on startup self.refresh()
def main(): """Start GUI """ app = QApplication([]) if sys.platform == "win32": myappid = 'tesseract.python.demo.{}'.format(__version__) # arbitrary string ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID(myappid) app.setWindowIcon(QIcon(':/images/appIcon')) window = MainWindow() window.show() app.exec_()
def main(): """Main Loop.""" print(__doc__ + __version__ + __url__) application = QApplication(sys.argv) application.setApplicationName("pyvoicechanger") application.setOrganizationName("pyvoicechanger") application.setOrganizationDomain("pyvoicechanger") application.setWindowIcon(QIcon.fromTheme("audio-input-microphone")) application.aboutToQuit.connect( lambda: call('killall rec ; killall play', shell=True)) mainwindow = MainWindow() mainwindow.show() sys.exit(application.exec_())
def main(): app = QApplication(sys.argv) app.setQuitOnLastWindowClosed(False) app.setOrganizationName('meteo-qt') app.setOrganizationDomain('meteo-qt') app.setApplicationName('meteo-qt') app.setWindowIcon(QIcon(':/logo')) filePath = os.path.dirname(os.path.realpath(__file__)) settings = QSettings() locale = settings.value('Language') if locale is None or locale == '': locale = QLocale.system().name() appTranslator = QTranslator() if os.path.exists(filePath + '/translations/'): appTranslator.load(filePath + "/translations/meteo-qt_" + locale) else: appTranslator.load("/usr/share/meteo_qt/translations/meteo-qt_" + locale) app.installTranslator(appTranslator) qtTranslator = QTranslator() qtTranslator.load("qt_" + locale, QLibraryInfo.location(QLibraryInfo.TranslationsPath)) app.installTranslator(qtTranslator) log_level = settings.value('Logging/Level') if log_level == '' or log_level is None: log_level = 'INFO' settings.setValue('Logging/Level', 'INFO') log_filename = os.path.dirname(settings.fileName()) if not os.path.exists(log_filename): os.makedirs(log_filename) log_filename = log_filename + '/meteo-qt.log' logging.basicConfig(format='%(asctime)s %(levelname)s: %(message)s - %(module)s - %(name)s', datefmt='%m/%d/%Y %H:%M:%S', filename=log_filename, level=log_level) logger = logging.getLogger('meteo-qt') logger.setLevel(log_level) handler = logging.handlers.RotatingFileHandler( log_filename, maxBytes=20, backupCount=5) logger1 = logging.getLogger() handler1 = logging.StreamHandler() logger1Formatter = logging.Formatter('%(levelname)s: %(message)s - %(module)s') handler1.setFormatter(logger1Formatter) logger.addHandler(handler) logger1.addHandler(handler1) m = SystemTrayIcon() app.exec_()
def __init__(self, app, account, homescreen, community_view, node_manager, widget, ui, label_icon, label_status, label_time, combo_referential, password_asker): """ Init :param sakia.core.app.Application app: application :param sakia.core.Account account: the account :param HomeScreenWidgetcreen homescreen: the homescreen :param CommunityView community_view: the community view :param NodeManager node_manager: the local node manager dialog :param QMainWindow widget: the widget of the main window :param Ui_MainWindow ui: the ui of the widget :param QLabel label_icon: the label of the icon in the statusbar :param QLabel label_status: the label of the status in the statusbar :param QLabel label_time: the label of the time in the statusbar :param QCombobox combo_referential: the combo of the referentials in the statusbar :param PasswordAsker password_asker: the password asker of the application :type: sakia.core.app.Application """ # Set up the user interface from Designer. super().__init__() self.app = app self.account = account self.initialized = False self.password_asker = password_asker self.import_dialog = None self.widget = widget self.ui = ui self.ui.setupUi(self.widget) self.widget.installEventFilter(self) QApplication.setWindowIcon(QIcon(":/icons/sakia_logo")) self.label_icon = label_icon self.status_label = label_status self.status_label.setTextFormat(Qt.RichText) self.label_time = label_time self.combo_referential = combo_referential self.combo_referential.setEnabled(False) self.combo_referential.currentIndexChanged[int].connect(self.referential_changed) self.homescreen = homescreen self.community_view = community_view self.node_manager = node_manager
def main(): logging.basicConfig(filename='log.txt', level=logging.DEBUG, filemode='w') # Redirect stdout and stderr to our logging file stdout_logger = logging.getLogger('STDOUT') stderr_logger = logging.getLogger('STDERR') sys.stdout = StreamToLogger(stdout_logger, logging.INFO) sys.stderr = StreamToLogger(stderr_logger, logging.ERROR) logging.info('Started ICE Control v' + __version__) app = QApplication(sys.argv) app_name = 'ICE Control' app.setOrganizationName("Vescent Photonics, Inc.") app.setOrganizationDomain("www.vescent.com") app.setApplicationName(app_name) app.setWindowIcon(QIcon("ui/vescent.ico")) view = QtQuick.QQuickView() if getattr(sys, 'frozen', False): # we are running in a |PyInstaller| bundle basedir = sys._MEIPASS else: # we are running in a normal Python environment basedir = os.path.dirname(os.path.abspath(__file__)) view.setTitle(app_name) context = view.rootContext() pyconsole = PyConsole(__version__) context.setContextProperty('python', pyconsole) ice = iceController() context.setContextProperty('ice', ice) view.setSource(QUrl("ui/main.qml")) view.engine().quit.connect(app.quit) view.show() app.exec_() #Cleanup: Manually delete QQuickView to prevent app crash del view ice.iceRef.disconnect() sys.exit(0)
def main(): app = QApplication(sys.argv) if sys.platform == "win32": app.setFont(QFont("Tahoma", 9)) app.setOrganizationName("Besteam") app.setOrganizationDomain("besteam.im") app.setApplicationName("QuickPanel") app.setQuitOnLastWindowClosed(False) app.setWindowIcon(QIcon(":/images/angelfish.png")) #app.setStyle(QStyleFactory.create("qtcurve")) platform = Platform() platform.start() try: getattr(app, "exec")() except AttributeError: getattr(app, "exec_")()
def __init__(self, app): """ Init :param sakia.core.app.Application app: application :type: sakia.core.app.Application """ # Set up the user interface from Designer. super().__init__() self.app = app self.initialized = False self.password_asker = None self.import_dialog = None super().setupUi(self) QApplication.setWindowIcon(QIcon(":/icons/sakia_logo")) self.app.version_requested.connect(self.latest_version_requested) self.status_label = QLabel("", self) self.status_label.setTextFormat(Qt.RichText) self.statusbar.addPermanentWidget(self.status_label, 1) self.label_time = QLabel("", self) self.statusbar.addPermanentWidget(self.label_time) self.combo_referential = QComboBox(self) self.combo_referential.setEnabled(False) self.combo_referential.currentIndexChanged.connect(self.referential_changed) self.statusbar.addPermanentWidget(self.combo_referential) self.homescreen = HomeScreenWidget(self.app, self.status_label) self.homescreen.frame_communities.community_tile_clicked.connect(self.change_community) self.homescreen.toolbutton_new_account.clicked.connect(self.open_add_account_dialog) self.homescreen.toolbutton_new_account.addAction(self.action_add_account) self.homescreen.toolbutton_new_account.addAction(self.action_import) self.homescreen.button_add_community.clicked.connect(self.action_open_add_community) self.homescreen.button_disconnect.clicked.connect(lambda :self.action_change_account("")) self.centralWidget().layout().addWidget(self.homescreen) self.homescreen.toolbutton_connect.setMenu(self.menu_change_account) self.community_view = CommunityWidget(self.app, self.status_label) self.community_view.button_home.clicked.connect(lambda: self.change_community(None)) self.community_view.button_certification.clicked.connect(self.open_certification_dialog) self.community_view.button_send_money.clicked.connect(self.open_transfer_money_dialog) self.centralWidget().layout().addWidget(self.community_view)
def gui_mode(): """ Start NEFI2 GUI """ myappid = 'nefi2.0' # arbitrary string if sys.platform == 'win32' or sys.platform == 'win64': ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID(myappid) extloader = ExtensionLoader() pipeline = Pipeline(extloader.cats_container) app = QApplication(sys.argv) app.setStyleSheet(qdarkstyle.load_stylesheet_pyqt5()) app.setQuitOnLastWindowClosed(True) app.setWindowIcon(QtGui.QIcon(os.path.join('icons', 'nefi2.ico'))) wnd = MainView(pipeline) wnd.load_dark_theme(app) wnd.show() sys.exit(app.exec_())
def main(): app = QApplication(sys.argv) app.setOrganizationName("University of Oldenburg") app.setOrganizationDomain("www.uni-oldenburg.de") app.setApplicationName("OptiSim") app.setWindowIcon(QIcon(":/OS_logo.png")) # Create and display the splash screen #splash_pix = QPixmap(":/OS_logo.png") #splash = QSplashScreen(splash_pix, QtCore.Qt.WindowStaysOnTopHint) #splash.setMask(splash_pix.mask()) #splash.show() #app.processEvents() wnd = MainWindow() wnd.show() #splash.finish(wnd) sys.exit(app.exec_())
def main(args=sys.argv): make_logger("unicodemoticon", emoji=True) lock = set_single_instance("unicodemoticon") check_encoding() set_process_name("unicodemoticon") set_process_priority() app = QApplication(args) app.setApplicationName("unicodemoticon") app.setOrganizationName("unicodemoticon") app.setOrganizationDomain("unicodemoticon") app.instance().setQuitOnLastWindowClosed(False) # no quit on dialog quit if qdarkstyle: app.setStyleSheet(qdarkstyle.load_stylesheet_pyqt5()) icon = QIcon(app.style().standardPixmap(QStyle.SP_FileIcon)) app.setWindowIcon(icon) mainwindow = MainWidget() mainwindow.show() mainwindow.hide() make_post_exec_msg(start_time) sys.exit(app.exec())
def main(): """Main Loop.""" log_file_path = os.path.join(gettempdir(), "vacap.log") log.basicConfig(level=-1, filemode="w", filename=log_file_path, format="%(levelname)s:%(asctime)s %(message)s %(lineno)s") log.getLogger().addHandler(log.StreamHandler(sys.stderr)) log.info(__doc__) log.debug("LOG File: '{}'.".format(log_file_path)) log.debug("Free Space on Disk: ~{} GigaBytes.".format( get_free_space_on_disk_on_gb(os.path.expanduser("~")))) log.debug("Running on Battery: {}".format(windows_is_running_on_battery())) signal.signal(signal.SIGINT, signal.SIG_DFL) # CTRL+C work to quit app app = QApplication(sys.argv) app.setApplicationName("vacap") app.setOrganizationName("vacap") app.setOrganizationDomain("vacap") icon = QIcon(app.style().standardPixmap(QStyle.SP_DriveFDIcon)) app.setWindowIcon(icon) win = MainWindow(icon) win.show() sys.exit(app.exec_())
def main(d): """Main Loop.""" make_root_check_and_encoding_debug() set_process_name_and_cpu_priority("websktop") set_single_instance("websktop") signal.signal(signal.SIGINT, signal.SIG_DFL) # CTRL+C work to quit app app = QApplication(sys.argv) app.setApplicationName("websktop") app.setOrganizationName("websktop") app.setOrganizationDomain("websktop") # app.instance().setQuitOnLastWindowClosed(False) # no quit on dialog quit icon = QIcon(app.style().standardPixmap(QStyle.SP_FileIcon)) app.setWindowIcon(icon) window = MainWindow() window.show() importd_thread = DThread(app, d) importd_thread.finished.connect(app.exit) # if ImportD Quits then Quit GUI app.aboutToQuit.connect(importd_thread.exit) # UI Quits then Quit ImportD importd_thread.start() make_post_execution_message() sys.exit(app.exec())
def main(): parser = get_parser() args = parser.parse_args() app = QApplication([]) app.setWindowIcon(QIcon(QPixmap(":/logo_small"))) app.setOrganizationName('Hardcoded Software') app.setApplicationName('moneyGuru') settings = QSettings() if args.debug: LOGGING_LEVEL = logging.DEBUG else: LOGGING_LEVEL = logging.DEBUG if adjust_after_deserialization(settings.value('DebugMode')) else logging.WARNING setupQtLogging(level=LOGGING_LEVEL, log_to_stdout=args.log_to_stdout) logging.debug('started in debug mode') if ISLINUX: stylesheetFile = QFile(':/stylesheet_lnx') else: stylesheetFile = QFile(':/stylesheet_win') stylesheetFile.open(QFile.ReadOnly) textStream = QTextStream(stylesheetFile) style = textStream.readAll() stylesheetFile.close() app.setStyleSheet(style) lang = settings.value('Language') locale_folder = op.join(BASE_PATH, 'locale') hscommon.trans.install_gettext_trans_under_qt(locale_folder, lang) # Many strings are translated at import time, so this is why we only import after the translator # has been installed from qt.app import MoneyGuru app.setApplicationVersion(MoneyGuru.VERSION) mgapp = MoneyGuru(filepath=args.filepath) install_excepthook('https://github.com/hsoft/moneyguru/issues') exec_result = app.exec_() del mgapp # Since PyQt 4.7.2, I had crashes on exit, and from reading the mailing list, it seems to be # caused by some weird crap about C++ instance being deleted with python instance still living. # The worst part is that Phil seems to say this is expected behavior. So, whatever, this # gc.collect() below is required to avoid a crash. gc.collect() return exec_result
INITIAL_PEAK_AREA = 10 INITIAL_PEAK_FWHM = 1 ALLOW_NEGATIVE_PEAKS = True def run(datalist, parameters): app = 0 # Fix for spyder crashing on consequent runs app = QApplication(sys.argv) main = MainWindow(datalist, parameters) main.show() sys.exit(app.exec_()) if __name__ == "__main__": app = 0 # Fix for spyder crashing on consequent runs app = QApplication(sys.argv) # This part needed for taskbar icon, see here: https://stackoverflow.com/questions/1551605/how-to-set-applications-taskbar-icon-in-windows-7 image_path = 'images/icon.png' if os.path.exists(image_path): import ctypes myappid = u'kbfi.peakfit.1.0' # arbitrary string ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID(myappid) app.setWindowIcon(QIcon(image_path)) select_files = SelectFilesWindow() select_files.show() sys.exit(app.exec_())
class App(Context): def __init__(self, headless: bool = False, icon_file=None, splash_file=None, splash_text=None, configs_file=None, log_file=None): self._headless = headless self._configs_file = configs_file self._icon_file = icon_file self._splash_file = splash_file self._splash_text = splash_text self._log_file = log_file self._settings: QSettings = None self._qt_application = None self._events_callback = {"create": [], "destroy": []} def on(self, event: str, callback: Callable[[Context], None]) -> NoReturn: if event not in self._events_callback: raise Exception("unsupported event %s" % event) self._events_callback[event].append(callback) def _notify_callback(self, event: str) -> NoReturn: if event not in self._events_callback: raise Exception("unsupported event %s" % event) for callback in self._events_callback[event]: callback(self) def on_create(self) -> NoReturn: self._notify_callback("create") def on_destroy(self) -> NoReturn: self._notify_callback("destroy") def run(self) -> int: setup_stdio() setup_console() run_as_job() argv = sys.argv[:] if self._headless: self._qt_application = QCoreApplication(argv) # Non-GUI signal.signal(signal.SIGINT, lambda *a: self._qt_application.quit()) else: self._qt_application = QApplication(argv) # icon if self._icon_file: self._window_icon = QtGui.QIcon(self._icon_file) self._qt_application.setWindowIcon(self._window_icon) # splash if self._splash_file: pixmap = QtGui.QPixmap(self._splash_file) self._splash = QSplashScreen(pixmap) if self._splash_text: self._set_splash_text(self._splash_text, "#ffffff") self._splash.show() # asyncqt asyncqt_ui_thread_loop.start_loop() # configs if self._configs_file: self._settings = QSettings(self._configs_file, QSettings.IniFormat) self._settings.sync() # log if self._log_file: logfp = open(self._log_file, 'w') STDERR_STREAMS.add(logfp) STDOUT_STREAMS.add(logfp) self._qt_application.aboutToQuit.connect(self._on_quit) self.on_create() # -> create and show the WebView window exit_code = self._qt_application.exec_() self._qt_application.deleteLater() return exit_code #sys.exit(exit_code) def _set_splash_text(self, text, color): self._splash.showMessage(text, alignment=QtCore.Qt.AlignHCenter | QtCore.Qt.AlignBottom, color=QtGui.QColor(color)) def set_main_window(self, window): if window: self._splash.finish(window) window.setWindowIcon(self._window_icon) def get_config(self, key, def_val=None): if self._settings: return self._settings.value(key, def_val) return def_val def _on_quit(self): self.on_destroy() def exit(self) -> NoReturn: self._qt_application.quit() def get_application_dir_path(self): return self._qt_application.applicationDirPath()
self.resize(400, 300) # 获取当前的状态栏(默认是有状态栏的) self.status = self.statusBar() # 设置状态栏显示的消息(消息只存在5s) self.status.showMessage('只显示5s的消息!', 5000) def center(self): # 获取屏幕坐标系 screen = QDesktopWidget().screenGeometry() # 获取窗口坐标系 size = self.geometry() left = (screen.width() - size.width()) / 2 top = (screen.height() - size.height()) / 2 # 移动窗口 self.move(left, top) if __name__ == '__main__': # 创建一个应用程序对象(传入参数) app = QApplication(sys.argv) # 设置应用程序的图标 app.setWindowIcon(QIcon('../images/Dragon.ico')) # 创建窗口类的对象 main = CenterMainWin() # 显示窗口 main.show() # 窗口居中 main.center() # 调用exit()进入程序的主循环 sys.exit(app.exec_())
def handle_close(self): self.close() class pop_check_class(QWidget): def __init__(self): super().__init__() self.initUI() def initUI(self): nonlocal des_list grud = QGridLayout() self.setLayout(grid) des_name_label = QLabel('DestinationName') # des_key_label = QLabel('DestinationKey') cnt = 0 for i in range(len(des_list)): checkBox = QCheckBox(txt,self) class main_window_class(QWidget): def __init__(self): super().__init__() self.initUI() def initUI(self): #self.statusBar().showMessage('Load completed') grid = QGridLayout() self.setLayout(grid) url_label = QLabel('CBS URL:') usr_label = QLabel('Username:'******'Password:'******'users.xml:') pgb_label = QLabel('Current Operation Progress:') inf_label = QLabel('''Guide: 1) Enter CBS URL. If your CBS address is https://ahsaycbs.com:1000, enter ahsaycbs.com:1000. 2) Enter username and password for a system user or API user. 3) Click List Destination(s) and wait for a popup Window. Choose which Predefined Destination you want to push the old quota to and click “Confirm”. Though this tool allows you to run it for multiple destinations at once, we would recommend you doing it for one destination each time to avoid confusion. 4) Click “Select…” and locate the users.xml’s backup you saved before upgrading to v7.15.6.x. You can find it in CBS\conf\Backup\dr-*date*.zip\conf\\users.xml if you haven’t kept it. 5) Click Analyse. This updater will generate a getUser.csv file to the directory where it resides in. It contains everything which will be pushed on to the server in the later stage. You can check or make amendments to it. The “Quota” will be pushed to the relative “User” for the “Destination” shown. 6) Click Update to start pushing quota updates to CBS. Final Report and Error Report will be outputted to the current directory. ''') self.url_edit = QLineEdit() self.usr_edit = QLineEdit() self.pwd_edit = QLineEdit() self.pwd_edit.setEchoMode(QLineEdit.Password) self.xml_edit = QLineEdit() #QLineEdit.setPlaceholderText(str):该属性包含行编辑的占位符文本。只要行编辑为空,设置此属性将使行编辑显示一个灰色的占位符文本。 #做自己version用,不用加一堆傻逼注释 lis_but = QPushButton('List Destination') sel_but = QPushButton('Select') ana_but = QPushButton('Analyse') upd_but = QPushButton('Update') grid.addWidget(url_label, 1, 0) grid.addWidget(self.url_edit, 1, 1, 1, 4) grid.addWidget(usr_label, 2, 0) grid.addWidget(self.usr_edit, 2, 1) grid.addWidget(pwd_label, 2, 2) grid.addWidget(self.pwd_edit, 2, 3) grid.addWidget(lis_but, 2, 4) grid.addWidget(xml_label, 3, 0) grid.addWidget(self.xml_edit, 3, 1, 1, 3) grid.addWidget(sel_but, 3, 4) grid.addWidget(ana_but, 4, 1) grid.addWidget(upd_but, 4, 3) upd_but.resize(upd_but.sizeHint()) ana_but.resize(upd_but.sizeHint()) # pb_label = QLabel('') # pb_bar = QProgressBar() self.pbar = QProgressBar() self.btn = QPushButton('Start') self.btn.clicked.connect(self.doAction) self.timer = QBasicTimer() self.step = 0 grid.addWidget(pgb_label, 5, 0, 1, 2) grid.addWidget(self.pbar, 6, 0, 1, 5) grid.addWidget(inf_label, 7, 0, 10, 5) self.url_edit.textChanged.connect(self.setUrl) self.usr_edit.textChanged.connect(self.setUsr) self.pwd_edit.textChanged.connect(self.setPwd) #add funcitons to the buttons lis_but.clicked.connect(listDest) sel_but.clicked.connect(self.findPath) ana_but.clicked.connect(testFromServer) upd_but.clicked.connect(submitToServer) grid.setSpacing(10) self.resize(600,600) self.center() self.setWindowTitle('Ahsay v7.15.6.x Quota Updater') self.show() def center(self): #用一个qr obj来存储self之后要放的位置 qr = self.frameGeometry() cp = QDesktopWidget().availableGeometry().center() qr.moveCenter(cp) self.move(qr.topLeft()) def timerEvent(self, e): if self.step >= 100: self.timer.stop() self.btn.setText('Finished') return self.step = self.step+1 self.pbar.setValue(self.step) def doAction(self): if self.timer.isActive(): self.timer.stop() self.btn.setText('Start') else: self.timer.start(100,self) self.btn.setText('Stop') def findPath(self, event): file_, filetype = QFileDialog.getOpenFileName(self) print(file_) self.xml_edit.setText(file_) nonlocal usr_xml_path usr_xml_path = file_ #这个 file_ 被echo了 #得到的是一个string def setUrl(self): nonlocal sysAd sysAd = self.url_edit.text() print('setUrl') print(sysAd) def setUsr(self): nonlocal sysUser sysUser = self.usr_edit.text() print('setUsr') print(sysUser) def setPwd(self): nonlocal sysPwd sysPwd = self.pwd_edit.text() print('setPwd') print(sysPwd) app = QApplication(sys.argv) app.setWindowIcon(QIcon('/Users/yanbingong/Desktop/装乱七八糟东西的文件夹/tt1.png')) main_window = main_window_class() sys.exit(app.exec_())
subList.append(line.split('|')) # print(subList) for i in subList: if i[0] == 'AUTHCODE' and i[1][0:10] in theList: return True else: pass return False # Autorun program if __name__ == '__main__': import sys from PyQt5.QtWidgets import QApplication app = QApplication(sys.argv) app.setWindowIcon(QIcon('Icon.ico')) try: if checkingDevice(): JnbTool = EditExcelFile() JnbTool.show() else: message = QMessageBox() message.setWindowTitle("Error!!!") message.setText("Error! Your device is not in the list!") message.show() app.exit() except: message = QMessageBox() message.setWindowTitle("Error!!!") message.setText("Error! ConnectionError or unknowError!")
import sys from PyQt5.QtWidgets import QMainWindow, QApplication, QPushButton from PyQt5.QtGui import QIcon class MainWidget(QMainWindow): def __init__(self, parent=None): super(MainWidget, self).__init__(parent) # 设置主窗体标签 self.setWindowTitle("QMainWindow 例子") self.resize(400, 200) btn = QPushButton("按钮") btn.setContentsMargins(0, 0, 0, 0) #设置中心Widget self.setCentralWidget(btn) self.status = self.statusBar() self.status.showMessage("这是状态栏提示", 5000) if __name__ == "__main__": app = QApplication(sys.argv) app.setWindowIcon(QIcon("./image/open.png")) main = MainWidget() main.show() sys.exit(app.exec_())
def run_dwarf(): """ fire it up """ #os.environ["QT_AUTO_SCREEN_SCALE_FACTOR"] = "1" os.environ["QT_SCALE_FACTOR"] = "1" os.environ["QT_AUTO_SCREEN_SCALE_FACTOR"] = "0" os.environ["QT_SCREEN_SCALE_FACTORS"] = "1" args = process_args() #_check_dependencies() # not enabled atm from lib import utils from lib.git import Git from lib.prefs import Prefs from ui.app import AppWindow _prefs = Prefs() local_update_disabled = _prefs.get('disable_local_frida_update', False) if not local_update_disabled: _git = Git() import frida remote_frida = _git.get_frida_version() local_frida = frida.__version__ if remote_frida and local_frida != remote_frida[0]['tag_name']: print('Updating local frida version to ' + remote_frida[0]['tag_name']) try: res = utils.do_shell_command('pip3 install frida --upgrade --user') if 'Successfully installed frida-' + remote_frida[0]['tag_name'] in res: _on_restart() elif 'Requirement already up-to-date' in res: if os.path.exists('.git_cache'): shutil.rmtree('.git_cache', ignore_errors=True) else: print('failed to update local frida') print(res) except Exception as e: # pylint: disable=broad-except, invalid-name print('failed to update local frida') print(str(e)) if os.name == 'nt': # windows stuff import ctypes try: # write ini to show folder with dwarficon folder_stuff = "[.ShellClassInfo]\n" folder_stuff += "IconResource=assets\\dwarf.ico,0\n" folder_stuff += "[ViewState]\n" folder_stuff += "Mode=\n" folder_stuff += "Vid=\n" folder_stuff += "FolderType=Generic\n" try: with open('desktop.ini', 'w') as ini: ini.writelines(folder_stuff) # set fileattributes to hidden + systemfile ctypes.windll.kernel32.SetFileAttributesW( r'desktop.ini', 0x02 | 0x04 ) # FILE_ATTRIBUTE_HIDDEN = 0x02 | FILE_ATTRIBUTE_SYSTEM = 0x04 except PermissionError: # its hidden+system already pass # fix for showing dwarf icon in windows taskbar instead of pythonicon _appid = u'iGio90.dwarf.debugger' ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID( _appid) ctypes.windll.user32.SetProcessDPIAware() except Exception: # pylint: disable=broad-except pass from PyQt5.QtCore import Qt from PyQt5.QtGui import QIcon from PyQt5.QtWidgets import QApplication qapp = QApplication([]) qapp.setDesktopSettingsAware(True) qapp.setAttribute(Qt.AA_EnableHighDpiScaling) qapp.setAttribute(Qt.AA_UseHighDpiPixmaps) qapp.setLayoutDirection(Qt.LeftToRight) qapp.setOrganizationName("https://github.com/iGio90/Dwarf") qapp.setApplicationName("dwarf") # set icon if os.name == "nt" and os.path.exists( utils.resource_path('assets/dwarf.ico')): _icon = QIcon(utils.resource_path('assets/dwarf.ico')) qapp.setWindowIcon(_icon) else: if os.path.exists(utils.resource_path('assets/dwarf.png')): _icon = QIcon(utils.resource_path('assets/dwarf.png')) qapp.setWindowIcon(_icon) app_window = AppWindow(args) app_window.setWindowIcon(_icon) app_window.onRestart.connect(_on_restart) try: sys.exit(qapp.exec_()) except SystemExit as sys_err: if sys_err.code == 0: # thanks for using dwarf print('Thank\'s for using Dwarf\nHave a nice day...') else: # something was wrong print('sysexit with: %d' % sys_err.code)
class MainChessApp(): """ The main application class """ def __init__(self): self.player = None #New Player self.app = QApplication([]) dir_ = QDir("fonts") #Set working directory #Set application details and icon self.app.setApplicationName("Chess Player") self.app.setApplicationDisplayName("Chess Player") self.app.setWindowIcon(QIcon("icons/chess_icon.ico")) #Get SettingsManager Instance self.settingsManager = SettingsManager() def buildUI(self): """ Build main window UI """ #Add The font _id = QFontDatabase.addApplicationFont("fonts/CenturyGothic.ttf") #set the application style self.setAppStyle() #Configure Window self.mainWindow = QWidget() self.mainWindow.setObjectName('window') self.mainWindow.setWindowTitle("Chess Player") #Window main layout v_layout = QVBoxLayout() # mainWindow layout h_layout = QHBoxLayout() # Placeholder for mainWindow buttons #Top Section logo = QLabel("Chess Player") logo_font = QFont("CenturyGothic", 38, QFont.Bold) logo.setFont(logo_font) logo.setStyleSheet("color: #0B5394;") v_layout.addWidget(logo) #Bottom Section self.capture_button = QPushButton("Start Capturing Board") self.capture_button.clicked.connect(self.captureBoard) self.motivation_button = QPushButton("Last Move") self.motivation_button.clicked.connect(lambda: self.showLastMove()) self.settings_button = QPushButton("Settings") self.settings_button.clicked.connect(self.openSettings) h_layout.addWidget(self.capture_button) h_layout.addWidget(self.motivation_button) h_layout.addWidget(self.settings_button) #Finalize layout v_layout.addLayout(h_layout) self.mainWindow.setLayout(v_layout) #Configure Window settings self.mainWindow.setFixedSize( self.mainWindow.sizeHint()) #Disable resize self.mainWindow.show() self.app.exec_() def setAppStyle(self): """ Change the application stylesheet """ self.app.setStyleSheet(app_styles) def changePlayerBoard(self, fen): """ Update the ChessPlayer Board """ if (self.player is None): self.player = ChessPlayer(fen.replace( "-", "/")) #replace fen output for futher processing else: self.player.setBoard(fen.replace( "-", "/")) #replace fen output for futher processing def captureBoard(self): """ Extract Board from the user's screen """ img = get_screen_image(self.mainWindow) board_found, board_image = extract_board(img) if (board_found): fen = extract_fen(board_image) self.changePlayerBoard(fen) self.player.setOutBoard( board_image) #change the output board image self.player.startBoardConfig( ) #Open the board configuration window else: QMessageBox.warning( self.mainWindow, 'Chess Player - No Board Found', "Couldn't find a chess board from your screen.", QMessageBox.Ok, QMessageBox.Ok) def openSettings(self): """ Open settings menu for potential modifications """ self.settingsManager.createUI() self.settingsManager.showUI() def showLastMove(self): """ Retrieve the last image produced by the ChessPlayer """ if self.player is not None and self.player.getLastMoveImage( ) is not None: cv2.imshow('Chess Player - The last move was', self.player.getLastMoveImage()) else: msg = QMessageBox() msg.setIcon(QMessageBox.Information) msg.setText( "You need to capture at least one board to show you the last move" ) msg.setWindowTitle("Chess Player - Nothing to show") msg.setStandardButtons(QMessageBox.Ok) msg.exec()
self.productID.currentText() + " ," + self.outStorageNo.text() + " ," + self.outTechState.text() + " ," + self.isReturn.currentText() + " ," + str(UserId) + " ," + self.createTime.text() + " ," + str(UserId) + " ," + self.createTime.text() + " ," + self.remark.toPlainText() + " ," + str(self.outCount.value()) + "]") db.close() confirm = QMessageBox.information(QDialog(), "提示", "出库信息新建成功!", QMessageBox.Yes, QMessageBox.Yes) if confirm == QMessageBox.Yes: self.dialog.close() else: logger.info("用户:" + str(UserId) + " 出库信息新建失败(重要数据输入值为空)") QMessageBox.information(QDialog(), "错误", "输入值不能为0或为空,请重新检查输入!", QMessageBox.Yes, QMessageBox.Yes) def cancel_fun(self): self.dialog.close() if __name__ == "__main__": app = QApplication(sys.argv) app.setWindowIcon(QIcon("../Images/MainWindow_1.png")) form = QWidget() w = AddOutStorage() w.setupUi(form) form.show() sys.exit(app.exec_())
@QtCore.pyqtSlot(int) def on_comboBox_currentIndexChanged(self, index): self.proxy.setFilterKeyColumn(index) class Browser(QWebEngineView): #(QWebView): windowList = [] def createWindow(self, QWebEnginePage_WebWindowType): new_webview = Browser() new_window = MainWindow() new_window.setCentralWidget(new_webview) new_window.show() self.windowList.append(new_window) return new_webview if __name__ == "__main__": import sys app = QApplication(sys.argv) app.setStyle("Fusion") app.setWindowIcon(QtGui.QIcon(':/icons/postman.ico')) # app.setStyleSheet("style.css") main = MainWindow() app.aboutToQuit.connect( main.shutdown) # connect to the shutdown method on the window. main.show() main.resize(400, 600) sys.exit(app.exec_())
def __init__(self): super().__init__() self.setObjectName('app') QApplication.setWindowIcon(QIcon(QPixmap(APP_ICON)))
#!/usr/bin/env python # -*- coding:utf-8 -*- # Author:ZhangYunFei import sys from PyQt5.QtWidgets import QApplication, QWidget from PyQt5.QtGui import QIcon class MyWidget(QWidget): def __init__(self): super().__init__() self.initUI() def initUI(self): self.setGeometry(300, 300, 300, 220) self.setWindowTitle("Icon") # windows 中设置左上角图标 self.setWindowIcon(QIcon("icon.jpg")) self.show() if __name__ == '__main__': app = QApplication(sys.argv) # 设置程序图标 app.setWindowIcon(QIcon("icon.jpg")) ex = MyWidget() sys.exit(app.exec_())
# from pysigview.config.system import SYS_INFO from pysigview.utils.qthelpers import add_actions, create_action from pysigview.widgets.dir_tree_dialog import DirTreeDialog from pysigview.widgets.preferences import Preferences # ============================================================================= # Get configuration # ============================================================================= from pysigview.config.main import CONF # ============================================================================= # Initialize QApp # ============================================================================= MAIN_APP = QApplication(sys.argv) APP_ICON = QIcon(get_image_path("pysigview.svg")) MAIN_APP.setWindowIcon(APP_ICON) QLocale.setDefault(QLocale(QLocale.C)) # ============================================================================= # Createspash screen # ============================================================================= SPLASH = QSplashScreen(QPixmap(get_image_path('splash.png'))) SPLASH_FONT = SPLASH.font() SPLASH_FONT.setPixelSize(10) SPLASH.setFont(SPLASH_FONT) SPLASH.show() SPLASH.showMessage("Initializing...", Qt.AlignBottom | Qt.AlignCenter | Qt.AlignAbsolute, QColor(Qt.black)) QApplication.processEvents()
def __init__(self, recording=None, exec=True, app=None, **kwargs): # Check if exist a default config file in the home (user) directory: mp.set_start_method("spawn", force=True) inum = kwargs.get("instance_number", -1) if inum >= 0: default_config_file = Path.home( ) / "stytra_setup_config_{}.json".format(inum) else: default_config_file = Path.home() / "stytra_setup_config.json" if default_config_file.is_file(): config = json.load(open(str(default_config_file))) else: config = dict() # Get rest of configuration parameters from the protocol: try: extra_config = kwargs["protocol"].stytra_config recursive_update(config, extra_config) except AttributeError: pass recursive_update(config, kwargs) # Use also keyword arguments if config.get("scope_triggering", None) == "zmq": # Automatically use zmqTrigger if zmq is specified from stytra.triggering import ZmqTrigger config["scope_triggering"] = ZmqTrigger(port="5555") if app is None: app = QApplication([]) app.setStyleSheet(qdarkstyle.load_stylesheet_pyqt5()) if app.devicePixelRatio() > 1: app.setAttribute(Qt.AA_UseHighDpiPixmaps) class_kwargs = dict(app=app) class_kwargs.update(config) base = VisualExperiment if "camera" in class_kwargs.keys(): base = CameraVisualExperiment if "tracking" in class_kwargs.keys(): base = TrackingExperiment if not class_kwargs["tracking"].get("embedded", True): class_kwargs["calibrator"] = CircleCalibrator() if recording: base = VideoRecordingExperiment # Stytra logo app_icon = QIcon() for size in [32, 64, 128, 256]: app_icon.addFile( pkg_resources.resource_filename(__name__, "/icons/{}.png".format(size)), QSize(size, size), ) app.setWindowIcon(app_icon) pg.setConfigOptions(imageAxisOrder="row-major") self.exp = base(**class_kwargs) self.exp.start_experiment() if exec: app.exec_()
def main(): """Main function.""" args = parse_commandline() if args.version_debug: import debuginfo sys.stdout.write(debuginfo.version_info_string() + '\n') sys.exit(0) if args.python_ly: # The python-ly path has to be inserted at the *second* position # because the first element in sys.path is the directory of the invoked # script (an information we need in determining if Frescobaldi is run # from its Git repository) sys.path.insert(1, args.python_ly) check_ly() if args.list_sessions: import sessions for name in sessions.sessionNames(): sys.stdout.write(name + '\n') sys.exit(0) urls = list(map(url, args.files)) if not app.qApp.isSessionRestored(): if not args.new and remote.enabled(): api = remote.get() if api: api.command_line(args, urls) api.close() sys.exit(0) if QSettings().value("splash_screen", True, bool): import splashscreen splashscreen.show() # application icon import icons QApplication.setWindowIcon(icons.get("frescobaldi")) QTimer.singleShot(0, remote.setup) # Start listening for IPC import mainwindow # contains MainWindow class import session # Initialize QSessionManager support import sessions # Initialize our own named session support # boot Frescobaldi-specific stuff that should be running on startup import viewhighlighter # highlight arbitrary ranges in text import progress # creates progress bar in view space import musicpos # shows music time in statusbar import autocomplete # auto-complete input import wordboundary # better wordboundary behaviour for the editor if sys.platform.startswith('darwin'): import macosx.setup macosx.setup.initialize() if app.qApp.isSessionRestored(): # Restore session, we are started by the session manager session.restoreSession(app.qApp.sessionKey()) return # Just create one MainWindow win = mainwindow.MainWindow() win.show() win.activateWindow() # make sure all dock tools are initialized and resized app.qApp.processEvents() # load specified session? doc = None if args.session and args.session != "-": doc = sessions.loadSession(args.session) # load documents given as arguments import document for u in urls: doc = win.openUrl(u, args.encoding, ignore_errors=True) if not doc: doc = document.EditorDocument(u, args.encoding) # were documents loaded? if not doc: if app.documents: doc = app.documents[-1] elif not args.session: # no docs, load default session doc = sessions.loadDefaultSession() if doc: win.setCurrentDocument(doc) else: win.cleanStart() if urls and args.line is not None: # set the last loaded document active and apply navigation if requested pos = doc.findBlockByNumber(args.line - 1).position() + args.column cursor = QTextCursor(doc) cursor.setPosition(pos) win.currentView().setTextCursor(cursor) win.currentView().centerCursor()
class DistUpgradeViewKDE(DistUpgradeView): """KDE frontend of the distUpgrade tool""" def __init__(self, datadir=None, logdir=None): DistUpgradeView.__init__(self) get_telemetry().set_updater_type('KDE') # silence the PyQt4 logger logger = logging.getLogger("PyQt4") logger.setLevel(logging.INFO) if not datadir or datadir == '.': localedir = os.path.join(os.getcwd(), "mo") else: localedir = "/usr/share/locale/ubuntu-release-upgrader" # FIXME: i18n must be somewhere relative do this dir try: gettext.bindtextdomain("ubuntu-release-upgrader", localedir) gettext.textdomain("ubuntu-release-upgrader") except Exception as e: logging.warning("Error setting locales (%s)" % e) # we test for DISPLAY here, QApplication does not throw a # exception when run without DISPLAY but dies instead if not "DISPLAY" in os.environ: raise Exception("No DISPLAY in os.environ found") # Force environment to make sure Qt uses suitable theming and UX. os.environ["QT_PLATFORM_PLUGIN"] = "kde" # For above settings to apply automatically we need to indicate that we # are inside a full KDE session. os.environ["KDE_FULL_SESSION"] = "TRUE" # We also need to indicate version as otherwise KDElibs3 compatibility # might kick in such as in QIconLoader.cpp:QString fallbackTheme. os.environ["KDE_SESSION_VERSION"] = "5" # Pretty much all of the above but for Qt5 os.environ["QT_QPA_PLATFORMTHEME"] = "kde" self.app = QApplication(["ubuntu-release-upgrader"]) # Try to load default Qt translations so we don't have to worry about # QStandardButton translations. translator = QTranslator(self.app) if type(PYQT_VERSION) == int: translator.load(QLocale.system(), 'qt', '_', '/usr/share/qt5/translations') else: translator.load(QLocale.system(), 'qt', '_', '/usr/share/qt4/translations') self.app.installTranslator(translator) QUrlOpener().setupUrlHandles() messageIcon = _icon( "system-software-update", fallbacks=[ "/usr/share/icons/oxygen/48x48/apps/system-software-update.png", "/usr/share/icons/hicolor/48x48/apps/adept_manager.png" ]) self.app.setWindowIcon(messageIcon) self.window_main = UpgraderMainWindow() self.window_main.setParent(self) self.window_main.show() self.prev_step = None # keep a record of the latest step self._opCacheProgress = KDEOpProgress( self.window_main.progressbar_cache, self.window_main.progress_text) self._acquireProgress = KDEAcquireProgressAdapter(self) self._cdromProgress = KDECdromProgressAdapter(self) self._installProgress = KDEInstallProgressAdapter(self) # reasonable fault handler sys.excepthook = self._handleException self.window_main.showTerminalButton.setEnabled(False) self.window_main.showTerminalButton.clicked.connect(self.showTerminal) # init gettext gettext.bindtextdomain("ubuntu-release-upgrader", localedir) gettext.textdomain("ubuntu-release-upgrader") self.translate_widget_children() name = _OSRelease().result["PRETTY_NAME"] if not name or name == "Ubuntu": name = "Kubuntu" self.window_main.label_title.setText( self.window_main.label_title.text().replace("Ubuntu", name)) # setup terminal text in hidden by default spot self.window_main.konsole_frame.hide() self.konsole_frame_layout = QHBoxLayout(self.window_main.konsole_frame) self.window_main.konsole_frame.setMinimumSize(600, 400) self.terminal_text = DumbTerminal(self._installProgress, self.window_main.konsole_frame) self.konsole_frame_layout.addWidget(self.terminal_text) self.terminal_text.show() # for some reason we need to start the main loop to get everything displayed # this app mostly works with processEvents but run main loop briefly to keep it happily displaying all widgets QTimer.singleShot(10, self.exitMainLoop) self.app.exec_() def exitMainLoop(self): print("exitMainLoop") self.app.exit() def translate_widget_children(self, parentWidget=None): if parentWidget == None: parentWidget = self.window_main if isinstance(parentWidget, QDialog) or isinstance( parentWidget, QWidget): if str(parentWidget.windowTitle()) == "Error": parentWidget.setWindowTitle( gettext.dgettext("kdelibs", "Error")) else: parentWidget.setWindowTitle(_(str(parentWidget.windowTitle()))) if parentWidget.children() != None: for widget in parentWidget.children(): self.translate_widget(widget) self.translate_widget_children(widget) def translate_widget(self, widget): if isinstance(widget, QLabel) or isinstance(widget, QPushButton): if str(widget.text()) == "&Cancel": kdelibs = gettext.translation("kdelibs", gettext.textdomain("kdelibs"), fallback=True) widget.setText(unicode_gettext(kdelibs, "&Cancel")) elif str(widget.text()) == "&Close": kdelibs = gettext.translation("kdelibs", gettext.textdomain("kdelibs"), fallback=True) widget.setText(unicode_gettext(kdelibs, "&Close")) elif str(widget.text()) != "": widget.setText(_(str(widget.text())).replace("_", "&")) def _handleException(self, exctype, excvalue, exctb): """Crash handler.""" if (issubclass(exctype, KeyboardInterrupt) or issubclass(exctype, SystemExit)): return # we handle the exception here, hand it to apport and run the # apport gui manually after it because we kill u-m during the upgrade # to prevent it from popping up for reboot notifications or FF restart # notifications or somesuch lines = traceback.format_exception(exctype, excvalue, exctb) logging.error("not handled exception in KDE frontend:\n%s" % "\n".join(lines)) # we can't be sure that apport will run in the middle of a upgrade # so we still show a error message here apport_crash(exctype, excvalue, exctb) if not run_apport(): tbtext = ''.join( traceback.format_exception(exctype, excvalue, exctb)) dialog = QDialog(self.window_main) loadUi("dialog_error.ui", dialog) self.translate_widget_children(self.dialog) dialog.crash_detail.setText(tbtext) # Make sure we have a suitable size depending on whether or not the view is shown dialog.adjustSize() dialog.exec_() sys.exit(1) def showTerminal(self): if self.window_main.konsole_frame.isVisible(): self.window_main.konsole_frame.hide() self.window_main.showTerminalButton.setText(_("Show Terminal >>>")) else: self.window_main.konsole_frame.show() self.window_main.showTerminalButton.setText(_("<<< Hide Terminal")) self.window_main.adjustSize() def getAcquireProgress(self): return self._acquireProgress def getInstallProgress(self, cache): self._installProgress._cache = cache return self._installProgress def getOpCacheProgress(self): return self._opCacheProgress def getCdromProgress(self): return self._cdromProgress def update_status(self, msg): self.window_main.label_status.setText(msg) def hideStep(self, step): image = getattr(self.window_main, "image_step%i" % step.value) label = getattr(self.window_main, "label_step%i" % step.value) image.hide() label.hide() def abort(self): step = self.prev_step if step: image = getattr(self.window_main, "image_step%i" % step.value) cancelIcon = _icon( "dialog-cancel", fallbacks=[ "/usr/share/icons/oxygen/16x16/actions/dialog-cancel.png", "/usr/lib/kde4/share/icons/oxygen/16x16/actions/dialog-cancel.png", "/usr/share/icons/crystalsvg/16x16/actions/cancel.png" ]) image.setPixmap(cancelIcon.pixmap(16, 16)) image.show() def setStep(self, step): super(DistUpgradeViewKDE, self).setStep(step) okIcon = _icon( "dialog-ok", fallbacks=[ "/usr/share/icons/oxygen/16x16/actions/dialog-ok.png", "/usr/lib/kde4/share/icons/oxygen/16x16/actions/dialog-ok.png", "/usr/share/icons/crystalsvg/16x16/actions/ok.png" ]) arrowIcon = _icon( "arrow-right", fallbacks=[ "/usr/share/icons/oxygen/16x16/actions/arrow-right.png", "/usr/lib/kde4/share/icons/oxygen/16x16/actions/arrow-right.png", "/usr/share/icons/crystalsvg/16x16/actions/1rightarrow.png" ]) if self.prev_step: image = getattr(self.window_main, "image_step%i" % self.prev_step.value) label = getattr(self.window_main, "label_step%i" % self.prev_step.value) image.setPixmap(okIcon.pixmap(16, 16)) image.show() ##arrow.hide() self.prev_step = step # show the an arrow for the current step and make the label bold image = getattr(self.window_main, "image_step%i" % step.value) label = getattr(self.window_main, "label_step%i" % step.value) image.setPixmap(arrowIcon.pixmap(16, 16)) image.show() label.setText("<b>" + label.text() + "</b>") def information(self, summary, msg, extended_msg=None): msg = "<big><b>%s</b></big><br />%s" % (summary, msg) dialogue = QDialog(self.window_main) loadUi("dialog_error.ui", dialogue) self.translate_widget_children(dialogue) dialogue.label_error.setText(msg) if extended_msg != None: dialogue.textview_error.setText(extended_msg) dialogue.textview_error.show() else: dialogue.textview_error.hide() dialogue.setWindowTitle(_("Information")) messageIcon = _icon( "dialog-information", fallbacks=[ "/usr/share/icons/oxygen/48x48/status/dialog-information.png", "/usr/lib/kde4/share/icons/oxygen/48x48/status/dialog-information.png", "/usr/share/icons/crystalsvg/32x32/actions/messagebox_info.png" ]) dialogue.image.setPixmap(messageIcon.pixmap(48, 48)) # Make sure we have a suitable size depending on whether or not the view is shown dialogue.adjustSize() dialogue.exec_() def error(self, summary, msg, extended_msg=None): msg = "<big><b>%s</b></big><br />%s" % (summary, msg) dialogue = QDialog(self.window_main) loadUi("dialog_error.ui", dialogue) self.translate_widget_children(dialogue) dialogue.label_error.setText(msg) if extended_msg != None: dialogue.textview_error.setText(extended_msg) dialogue.textview_error.show() else: dialogue.textview_error.hide() messageIcon = _icon( "dialog-error", fallbacks=[ "/usr/share/icons/oxygen/48x48/status/dialog-error.png", "/usr/lib/kde4/share/icons/oxygen/48x48/status/dialog-error.png", "/usr/share/icons/crystalsvg/32x32/actions/messagebox_critical.png" ]) dialogue.image.setPixmap(messageIcon.pixmap(48, 48)) # Make sure we have a suitable size depending on whether or not the view is shown dialogue.adjustSize() dialogue.exec_() return False def confirmChanges(self, summary, changes, demotions, downloadSize, actions=None, removal_bold=True): """show the changes dialogue""" # FIXME: add a whitelist here for packages that we expect to be # removed (how to calc this automatically?) DistUpgradeView.confirmChanges(self, summary, changes, demotions, downloadSize) self.changesDialogue = QDialog(self.window_main) loadUi("dialog_changes.ui", self.changesDialogue) self.changesDialogue.treeview_details.hide() self.changesDialogue.buttonBox.helpRequested.connect( self.showChangesDialogueDetails) self.translate_widget_children(self.changesDialogue) self.changesDialogue.buttonBox.button(QDialogButtonBox.Ok).setText( _("&Start Upgrade")) self.changesDialogue.buttonBox.button(QDialogButtonBox.Help).setIcon( QIcon()) self.changesDialogue.buttonBox.button( QDialogButtonBox.Help).setText(_("Details") + " >>>") messageIcon = _icon( "dialog-warning", fallbacks=[ "/usr/share/icons/oxygen/48x48/status/dialog-warning.png", "/usr/lib/kde4/share/icons/oxygen/48x48/status/dialog-warning.png", "/usr/share/icons/crystalsvg/32x32/actions/messagebox_warning.png" ]) self.changesDialogue.question_pixmap.setPixmap( messageIcon.pixmap(48, 48)) if actions != None: cancel = actions[0].replace("_", "") self.changesDialogue.buttonBox.button( QDialogButtonBox.Cancel).setText(cancel) confirm = actions[1].replace("_", "") self.changesDialogue.buttonBox.button( QDialogButtonBox.Ok).setText(confirm) summaryText = "<big><b>%s</b></big>" % summary self.changesDialogue.label_summary.setText(summaryText) self.changesDialogue.label_changes.setText(self.confirmChangesMessage) # fill in the details self.changesDialogue.treeview_details.clear() self.changesDialogue.treeview_details.setHeaderLabels(["Packages"]) self.changesDialogue.treeview_details.header().hide() for demoted in self.demotions: self.changesDialogue.treeview_details.insertTopLevelItem( 0, QTreeWidgetItem(self.changesDialogue.treeview_details, [_("No longer supported %s") % demoted.name])) for rm in self.toRemove: self.changesDialogue.treeview_details.insertTopLevelItem( 0, QTreeWidgetItem(self.changesDialogue.treeview_details, [_("Remove %s") % rm.name])) for rm in self.toRemoveAuto: self.changesDialogue.treeview_details.insertTopLevelItem( 0, QTreeWidgetItem( self.changesDialogue.treeview_details, [_("Remove (was auto installed) %s") % rm.name])) for inst in self.toInstall: self.changesDialogue.treeview_details.insertTopLevelItem( 0, QTreeWidgetItem(self.changesDialogue.treeview_details, [_("Install %s") % inst.name])) for up in self.toUpgrade: self.changesDialogue.treeview_details.insertTopLevelItem( 0, QTreeWidgetItem(self.changesDialogue.treeview_details, [_("Upgrade %s") % up.name])) # Use a suitable size for the window given the current content. self.changesDialogue.adjustSize() #FIXME resize label, stop it being shrinkable res = self.changesDialogue.exec_() if res == QDialog.Accepted: return True return False def showChangesDialogueDetails(self): if self.changesDialogue.treeview_details.isVisible(): self.changesDialogue.treeview_details.hide() self.changesDialogue.buttonBox.button( QDialogButtonBox.Help).setText(_("Details") + " >>>") else: self.changesDialogue.treeview_details.show() self.changesDialogue.buttonBox.button( QDialogButtonBox.Help).setText("<<< " + _("Details")) self.changesDialogue.adjustSize() def askYesNoQuestion(self, summary, msg, default='No'): answer = QMessageBox.question(self.window_main, summary, "<font>" + msg, QMessageBox.Yes | QMessageBox.No, QMessageBox.No) if answer == QMessageBox.Yes: return True return False def confirmRestart(self): messageBox = QMessageBox( QMessageBox.Question, _("Restart required"), _("<b><big>Restart the system to complete the upgrade</big></b>"), QMessageBox.NoButton, self.window_main) yesButton = messageBox.addButton(QMessageBox.Yes) noButton = messageBox.addButton(QMessageBox.No) yesButton.setText(_("_Restart Now").replace("_", "&")) noButton.setText(gettext.dgettext("kdelibs", "&Close")) answer = messageBox.exec_() if answer == QMessageBox.Yes: return True return False def processEvents(self): QApplication.processEvents() def pulseProgress(self, finished=False): # FIXME: currently we do nothing here because this is # run in a different python thread and QT explodes if the UI is # touched from a non QThread pass def on_window_main_delete_event(self): #FIXME make this user friendly text = _("""<b><big>Cancel the running upgrade?</big></b> The system could be in an unusable state if you cancel the upgrade. You are strongly advised to resume the upgrade.""" ) text = text.replace("\n", "<br />") cancel = QMessageBox.warning(self.window_main, _("Cancel Upgrade?"), text, QMessageBox.Yes, QMessageBox.No) if cancel == QMessageBox.Yes: return True return False
def statusMsg(self, message): if message is not None: self.statusBar().showMessage(message) '''刷新运行日志事件''' def actListenersRunLogs(self, title=''): if (self.listeners['RunLogsTab'] is not None): self.listeners['RunLogsTab']() pass if __name__ == '__main__': curPath, curFilename = os.path.split(os.path.abspath(sys.argv[0])) rootPath = curPath.replace("\\", "/") app = QApplication(sys.argv) App = Main() App.mainFrame = WinMain(App) App.initMain() app.setWindowIcon(QtGui.QIcon(':icons/images/winlogo.png')) try: if (App.login()): App.show() sys.exit(app.exec_()) except Exception as e: App.closeMain()
self.action2_2.triggered.connect(self.juji) self.action1_3.triggered.connect(self.yugao) self.widget_2.hide() def yugao(self): QtGui.QDesktopServices.openUrl(QtCore.QUrl('https://movie.douban.com/trailer/251878/')) def openUrl(self): QtGui.QDesktopServices.openUrl(QtCore.QUrl('https://baike.baidu.com/item/%E7%BD%97%E5%B0%8F%E9%BB%91%E6%88%98%E8%AE%B0/8383472?fr=aladdin')) def juji(self): QtGui.QDesktopServices.openUrl(QtCore.QUrl('https://www.bilibili.com/bangumi/play/ep32374/?share_medium=web&share_source=qq&bbid=5758CC01-5759-40AE-970F-FE1CDF5DE9A31613infoc&ts=1568732453499')) def center(self): screen = QDesktopWidget().screenGeometry()#获取屏幕坐标系 size = self.geometry()#获取窗口坐标 newleft = (screen.width() - size.width()) / 2 newtop = (screen.height() - size.height()) / 2 self.move(newleft.newtop) # def rewujieshao(self): if __name__ == "__main__": app = QApplication(sys.argv) app.setWindowIcon(QIcon('images/tubiao1.ico')) mywin = mymainwindow() mywin.show() sys.exit(app.exec_())
def main(): global app app = QApplication([]) app.setWindowIcon(QIcon(ICON['application'])) parser = ArgumentParser(prog='wonambi', description=DESCRIPTION) parser.add_argument('-v', '--version', action='store_true', help='Return version') parser.add_argument('-l', '--log', default='info', help='Logging level: info (default), debug') parser.add_argument('--reset', action='store_true', help='Reset (clear) configuration file') parser.add_argument('--bids', action='store_true', help='Read the information stored in the BIDS format') parser.add_argument('dataset', nargs='?', help='full path to dataset to open') parser.add_argument('annot', nargs='?', help='full path to annotations file to open') parser.add_argument('montage', nargs='?', help='full path to montage file to open') args = parser.parse_args() DATE_FORMAT = '%H:%M:%S' if args.log[:1].lower() == 'i': lg.setLevel(INFO) FORMAT = '{asctime:<10}{message}' elif args.log[:1].lower() == 'd': lg.setLevel(DEBUG) FORMAT = '{asctime:<10}{levelname:<10}{filename:<40}(l. {lineno: 6d})/ {funcName:<40}: {message}' formatter = Formatter(fmt=FORMAT, datefmt=DATE_FORMAT, style='{') handler = StreamHandler() handler.setFormatter(formatter) lg.handlers = [] lg.addHandler(handler) if args.reset: settings.clear() if args.version: lg.info('WONAMBI v{}'.format(__version__)) else: q = MainWindow() q.show() if args.dataset: q.info.open_dataset(args.dataset, bids=args.bids) if args.annot: q.notes.update_notes(args.annot) if args.montage: q.channels.load_channels(test_name=args.montage) app.exec()
from PyQt5.QtWidgets import QApplication, QMainWindow, QStackedWidget, QPushButton from PyQt5.uic import loadUi from PyQt5.QtGui import QIcon from UI.change import Change change = None class main(QMainWindow): def __init__(self): super(main, self).__init__() loadUi('UI.ui', self) stacked_widget = self.findChild(QStackedWidget, "StackedWidget") change = Change() change.stacked_widget = stacked_widget change.main_window = self welcomeButton = self.findChild(QPushButton, "WelcomePageButton") welcomeButton.clicked.connect(lambda: change.change_page(change, 1)) app = QApplication(sys.argv) app_icon = QIcon("UI.png") app.setWindowIcon(app_icon) widget = main() widget.show() sys.exit(app.exec_())
def __init__(self): QMainWindow.__init__(self) self.setupUi(self) self.pbConnect.setProperty("css", True) self.pageHost.setMain(self) self.pageHost.connectPressed.connect(self.onConnectHost) self.pageHost.cancelPressed.connect(self.showPage) self.pageLogin.setMain(self) self.pageLogin.connectPressed.connect(self.onConnectLogin) self.pageLogin.cancelPressed.connect(self.showPage) self.pageAbout.setMain(self) self.pageAbout.okPressed.connect(self.showPage) self.loaded = False self.setWindowTitle('Gold Drive') app_icon = QIcon() app_icon.addFile(':/images/icon_16.png', QSize(16, 16)) app_icon.addFile(':/images/icon_32.png', QSize(32, 32)) app_icon.addFile(':/images/icon_64.png', QSize(64, 64)) app_icon.addFile(':/images/icon_128.png', QSize(128, 128)) QApplication.setWindowIcon(app_icon) stream = QFile(':/style/style.css') if stream.open(QIODevice.ReadOnly | QFile.Text): self.setStyleSheet(QTextStream(stream).readAll()) # initial values from settings self.settings = QSettings("sganis", "golddrive") if self.settings.value("geometry"): self.restoreGeometry(self.settings.value("geometry")) self.restoreState(self.settings.value("windowState")) self.progressBar.setVisible(False) self.lblMessage.setText("") # self.widgetPassword.setVisible(False) self.returncode = util.ReturnCode.NONE # read config.json self.configfile = fr'{util.DIR}\..\config.json' self.param = {} self.config = util.load_config(self.configfile) # path = os.environ['PATH'] # sshfs_path = self.config.get('sshfs_path','') # sanfs_path = self.config.get('sanfs_path','') # os.environ['PATH'] = fr'{sanfs_path};{sshfs_path};{path}' self.updateCombo(self.settings.value("cboParam", 0)) self.fillParam() self.lblUserHostPort.setText(self.param['userhostport']) menu = Menu(self.pbHamburger) menu.addAction('&Connect', self.mnuConnect) menu.addAction('&Disconnect', self.mnuDisconnect) menu.addAction('Disconnect &all drives', self.mnuDisconnectAll) menu.addAction('&Open program location', self.mnuOpenProgramLocation) menu.addAction('Open &terminal', self.mnuOpenTerminal) menu.addAction('Open &log file', self.mnuOpenLogFile) menu.addAction('&Restart Explorer.exe', self.mnuRestartExplorer) menu.addAction('&About...', self.mnuAbout) self.pbHamburger.setMenu(menu) # worker for commands self.worker = Worker() self.worker.workDone.connect(self.onWorkDone) # worker for update self.updater = Updater(self.config["update_url"]) self.updater.checkDone.connect(self.onCheckUpdateDone) self.updater.doCheck() # worker for watching config.json changes self.watcher = QFileSystemWatcher() self.watcher.addPaths([self.configfile]) self.watcher.fileChanged.connect(self.onConfigFileChanged) self.checkDriveStatus() self.showPage(util.Page.MAIN) self.lblMessage.linkActivated.connect(self.on_lblMessage_linkActivated) self.loaded = True
# reset config file if args.reset: mainAppWindow.cfg.saveDefaultConfig() #cfg = toml.load(theConfig) # Create and show splash screen # pixmap = QPixmap(":splash.png") # splash = QSplashScreen(pixmap) # splash.show() app.processEvents() # print(QStyleFactory.keys()) app.setStyle("Fusion") # Setting the Application Icon on Windows app.setWindowIcon(QIcon(":windows-main.ico")) # Set application window size, 800 x 600 by default if len(args.size) == 1: screen_resolution = app.desktop().screenGeometry() mainAppWindow.cfg['global']['screenWidth'], mainAppWindow.cfg['global']['screenHeight'] = \ screen_resolution.width(), screen_resolution.height() elif len(args.size) == 2: mainAppWindow.cfg['global']['screenWidth'], mainAppWindow.cfg['global']['screenHeight'] = \ args.size[0], args.size[1] else: pass mainAppWindow.show() # Close the splash screen # splash.finish(mainAppWindow)
return norm_list def ok_continue(self): print("inside ok_continue") if self.dirty: reply = QMessageBox.question( self, "Image Changer - Unsaved Changes", "Save unsaved changes?", QMessageBox.Yes | QMessageBox.No | QMessageBox.Cancel) if reply == QMessageBox.Cancel: return False elif reply == QMessageBox.Yes: self.file_save() print("Dirty: ", self.dirty) new_image = self.image.convertToFormat(4) return True # --------------------------------------------------------------- if __name__ == "__main__": app = QApplication(sys.argv) app.setOrganizationName("Kerr & Associates") app.setOrganizationDomain("edkerrassociates.com") app.setApplicationName("Image Changer") app.setWindowIcon(QIcon(":/icon")) form = MainWindow() form.show() app.exec_()
super(FirstMainWin, self).__init__() #设置主窗口的标题 self.setWindowTitle('朱浩的第一个主窗口应用') #设置窗口的尺寸 self.resize(400, 600) self.status = self.statusBar() self.status.showMessage('只存在10秒的消息', 10000) def center(self): #获取屏幕坐标系 screen = QDesktopWidget().screenGeometry() #获取窗口坐标系 size = self.geometry() newLeft = (screen.width() - size.width()) / 2 newTop = (screen.height() - size.height()) / 2 self.move(newLeft, newTop) if __name__ == '__main__': app = QApplication(sys.argv) app.setWindowIcon(QIcon('../Icons/LogicAnalyser.ico')) main = FirstMainWin() main.show() #main.center() sys.exit(app.exec_())
self.edit.copy() # выровнять положение CharacterWidget в scroll_area def adjustMapPos(self, pos): row = pos // self.chars.cell_size self.scroll_area.verticalScrollBar().setValue(row * self.chars.cell_size) def keyPressEvent(self, event): if event.key() == Qt.Key_F1: QMessageBox.aboutQt(self, "Ҏγ†øη " + sys.version) if event.key() == Qt.Key_Escape: self.close() def closeEvent(self, event): self.settings.lang = self.table.lang self.settings.bookmarks = [ self.bookmarks.itemText(i) for i in range(self.bookmarks.count()) ] self.settings.editstring = self.edit.text() self.settings.save() if __name__ == '__main__': app = QApplication(sys.argv) app.setWindowIcon(QIcon('icons/favicon.ico')) mainWidget = Main() mainWidget.show() sys.exit(app.exec_())
rows = pyqtSignal(QTableWidget, list) info = pyqtSignal(str, str, str, str) def __init__(self): super().__init__() self.rows.connect(update_rows) self.info.connect(info) self.block = False sig = SignalsProvider() update_data(window.ls) icon = QIcon(os.path.join(ROOT, "qt.png")) app.setWindowIcon(icon) window.show() def _d_bunch(w): threading.Thread(target=download_bunch, args=(w, )).start() def _r_bunch(w): threading.Thread(target=run_bunch, args=(w, )).start() def download_bunch(w): repos = get_installed_repos() for i in range(w.rowCount()): if w.item(i, 0).checkState() == QtCore.Qt.Checked:
def refresh_data(self): sql="SELECT staId,staName,origin_salary FROM salary order by staId" type=1 data=LinkMysql().select_single(sql,type) #数据的大小 row = len(data) vol = len(data[0]) self.MyTable.setRowCount(row) #构建表格插入数据 for i in range(row): for j in range(vol): temp_data = data[i][j] # 临时记录,不能直接插入表格 self.data1 = QTableWidgetItem(str(temp_data)) # 转换后可插入表格 self.MyTable.setItem(i, j, self.data1) print('This is refresh-area') if __name__ == "__main__": app = QApplication(sys.argv) app.setWindowIcon(QIcon("./source/staff.png")) app.setStyleSheet(qdarkstyle.load_stylesheet_pyqt5()) c = salary_staff_console() c.show() sys.exit(app.exec_())
def view_volume(vol=None, args=None, window_name=None): global PARAM_WIDTH, SCROLL_WIDTH, UI_EXTRA_SCALING, CLIPBOARD, app if window_name is None: window_name = APP_NAME if args is None: args = sys.argv QApplication.setAttribute(Qt.AA_EnableHighDpiScaling) QApplication.setAttribute(Qt.AA_UseHighDpiPixmaps, True) app = QApplication(args) if LOGICAL_DPI_BASELINE is not None: # This is used to fix fractional scaling in Windows, which does # not show up as a devicePixelRatio! UI_EXTRA_SCALING = QWidget().logicalDpiX() / LOGICAL_DPI_BASELINE PARAM_WIDTH = int(PARAM_WIDTH * UI_EXTRA_SCALING) SCROLL_WIDTH = int(SCROLL_WIDTH * UI_EXTRA_SCALING) app.setStyle('Fusion') app.setPalette(generateDarkPalette()) app.setStyleSheet(f''' QWidget {{ font-size: {int(12 * UI_EXTRA_SCALING)}px; }} QLabel, QSlider, QSpinBox, QDoubleSpinBox, QCheckBox {{ padding: 0px; margin: 0px; }} QGroupBox {{ padding: 0px; padding-top: 20px; margin: 0px; }} QScrollBar:vertical {{ width: {SCROLL_WIDTH}px; }} #Border {{ border: 1px solid #808080; border-radius: 4px; margin-top: 0px; margin-bottom: 5px; }} QTabBar::tab:selected {{ color: palette(Text); }} QTabBar::tab:!selected {{ color: #A0A0A0; }} ''') app.setApplicationDisplayName(window_name) window = VolumetricViewer(clipboard=app.clipboard(), window_name=window_name) if vol is not None: window.openData(vol) app.setWindowIcon( QtGui.QIcon(QtGui.QPixmap(os.path.join(ICON_DIR, 'muvi_logo.png')))) return (app.exec())
df = pd.read_csv('SMSSpamCollection.txt', delimiter='\t', header=None) y, X_train = df[0], df[1] vectorizer = TfidfVectorizer() X = vectorizer.fit_transform(X_train) lr = linear_model.LogisticRegression() lr.fit(X, y) testX = vectorizer.transform( ['URGENT! Your mobile No. 1234 was awarded a Prize']) predictions = lr.predict(testX) print(predictions) from PyQt5.QtWidgets import QMainWindow, QApplication from PyQt5.QtGui import QIcon from mainWindow import MainWindow from scipy import _distributor_init # from scipy import spatial.ck if __name__ == "__main__": import sys app = QApplication(sys.argv) app.setWindowIcon(QIcon("./images/cartoon1.ico")) myWin = MainWindow() myWin.show() sys.exit(app.exec_()) input("输入任意键结束")
class CenterForm(QMainWindow): def __init__(self, parent=None): super(CenterForm, self).__init__(parent) # 设置主窗口标题 self.setWindowTitle('第一个主窗口应用') # 设置窗口尺寸 self.resize(400, 300) self.center() def center(self): #获取屏幕坐标系 screen = QDesktopWidget().screenGeometry() #获取窗口坐标系 newLeft = (screen.width() - self.width()) / 2 newRight = (screen.height() - self.height()) / 2 self.move(newLeft, newRight) if __name__ == '__main__': app = QApplication(sys.argv) app.setWindowIcon(QIcon('../images/qq.ico')) main = CenterForm() main.show() sys.exit(app.exec_())