我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用PyQt5.QtWidgets.QApplication()。
def main(): app = QtWidgets.QApplication(sys.argv) MainWindow = QtWidgets.QMainWindow() ui = DottorrentGUI() ui.setupUi(MainWindow) MainWindow.resize(500, 0) MainWindow.setGeometry( QtWidgets.QStyle.alignedRect( QtCore.Qt.LeftToRight, QtCore.Qt.AlignCenter, MainWindow.size(), app.desktop().availableGeometry() ) ) MainWindow.setWindowTitle(PROGRAM_NAME_VERSION) ui.loadSettings() ui.clipboard = app.clipboard app.aboutToQuit.connect(lambda: ui.saveSettings()) MainWindow.show() sys.exit(app.exec_())
def main(): app = QtWidgets.QApplication(sys.argv) queue = Queue() thread = QtCore.QThread() receiver = MessageReceiver(queue) window = RedditDownloaderGUI(queue, receiver) receiver.output_signal.connect(window.update_output) receiver.moveToThread(thread) thread.started.connect(receiver.run) receiver.finished.connect(thread.quit) receiver.finished.connect(receiver.deleteLater) thread.finished.connect(thread.deleteLater) thread.start() window.show() sys.exit(app.exec_())
def main(): app = QApplication (sys.argv) tree = QTreeWidget () headerItem = QTreeWidgetItem() item = QTreeWidgetItem() for i in range(3): parent = QTreeWidgetItem(tree) parent.setText(0, "Parent {}".format(i)) parent.setFlags(parent.flags() | Qt.ItemIsTristate | Qt.ItemIsUserCheckable) for x in range(5): child = QTreeWidgetItem(parent) child.setFlags(child.flags() | Qt.ItemIsUserCheckable) child.setText(0, "Child {}".format(x)) child.setCheckState(0, Qt.Unchecked) tree.show() sys.exit(app.exec_())
def mainPyQt5(): # ?????????import from PyQt5.QtWidgets import QApplication from PyQt5.QtCore import QUrl from PyQt5.QtWebEngineWidgets import QWebEngineView url = 'https://github.com/tody411/PyIntroduction' app = QApplication(sys.argv) # QWebEngineView???Web????? browser = QWebEngineView() browser.load(QUrl(url)) browser.show() sys.exit(app.exec_())
def main(): """Run StarCraft Casting Tool.""" global language from scctool.view.main import MainWindow currentExitCode = MainWindow.EXIT_CODE_REBOOT cntlr = None while currentExitCode == MainWindow.EXIT_CODE_REBOOT: try: app = QApplication(sys.argv) app.setStyle(QStyleFactory.create('Fusion')) translator = QTranslator(app) translator.load(QLocale(language), "qtbase", "_", getAbsPath('locales'), ".qm") app.installTranslator(translator) initial_download() cntlr = main_window(app, translator, cntlr) currentExitCode = app.exec_() app = None except Exception as e: logger.exception("message") sys.exit(currentExitCode)
def __test__send(self): data = str("G29"+'\n') print('0') #if self._serial_context_.isRunning(): print("1") if len(data) > 0: print("2") self._serial_context_.send(data, 0) print(data) # def __run__(self): # import sys # print("123") # app = QtWidgets.QApplication(sys.argv) # Dialog = QtWidgets.QDialog() # ui = Ui_Dialog() # ui.setupUi(Dialog) # Dialog.show() # sys.exit(app.exec_())
def mainPyQt4Simple(): # ?????????import from PyQt4.QtCore import QUrl from PyQt4.QtGui import QApplication from PyQt4.QtWebKit import QWebView url = 'https://github.com/tody411/PyIntroduction' app = QApplication(sys.argv) # QWebView???Web????? browser = QWebView() browser.load(QUrl(url)) browser.show() sys.exit(app.exec_()) ## PyQt4??Web???????(Youtube?).
def main(): global app app = QtWidgets.QApplication(sys.argv) my_args = parse_args(app.arguments()) main_window = MainWindow() setup_logger(main_window, debug=my_args.debug) if my_args.full_load: AutoConsumed._timeout = float('inf') if my_args.repo_path: QtCore.QMetaObject.invokeMethod( main_window, 'open_repo', Qt.Qt.QueuedConnection, QtCore.Q_ARG(str, my_args.repo_path), ) main_window.show() return app.exec_()
def run(): app = QtWidgets.QApplication(sys.argv) # Translates standard-buttons (Ok, Cancel) and mac menu bar to german try: base_path = sys._MEIPASS except Exception: base_path = os.path.abspath(".") path = os.path.join(base_path, 'bin', 'qtbase_de.qm') translator = QtCore.QTranslator() translator.load(path) app.installTranslator(translator) window = MainWindow() window.show() app.exec_()
def main(args=None): app = QW.QApplication(sys.argv) if len(sys.argv) == 2: argument = sys.argv[1] if os.path.exists(argument): browser = Browser("file:///" + os.path.abspath(argument)) elif isurl_reachable(argument): if argument.startswith("www"): print("http://" + argument) browser = Browser("http://" + argument) else: browser = Browser(argument) else: print("{} not a local file or reachable URL".format(argument)) browser = Browser("http://sequana.readthedocs.org/en/master") else: browser = Browser("http://sequana.readthedocs.org/en/master") browser.show() sys.exit(app.exec_())
def start_qt_scene_app(inbox=None, outbox=None, ping=False): """ Starts a simple QtApp with a TurtleScene widget. Args: inbox/outbox: Inbox/Outbox queues used for IPC. """ from .view import TurtleView app = QtWidgets.QApplication(sys.argv) scene = TurtleScene(inbox=inbox, outbox=outbox) window = TurtleView(scene) window.setWindowTitle('Turtle') window.setMinimumWidth(800) window.setMinimumHeight(600) if ping: scene.ping(receive=True) window.show() sys.exit(app.exec_())
def main(): """ The main function of the application. It will create a QApplication and a main window then run the application and exit. """ app = QApplication(sys.argv) qtTranslator = QTranslator() translate_path = os.path.join( settings.TRANSLATE_DIR, "SiviCNCDriver_" + QLocale.system().name() ) qtTranslator.load(translate_path) app.installTranslator(qtTranslator) window = MainWindow() window.show() sys.exit(app.exec())
def window(): app = QtWidgets.QApplication(sys.argv) w = QtWidgets.QWidget() b = QtWidgets.QPushButton('Push Me') l = QtWidgets.QLabel('Look at me') h_box = QtWidgets.QHBoxLayout() h_box.addStretch() h_box.addWidget(l) h_box.addStretch() v_box = QtWidgets.QVBoxLayout() v_box.addWidget(b) v_box.addLayout(h_box) w.setLayout(v_box) w.setWindowTitle('PyQt5 Lesson 4') w.show() sys.exit(app.exec_())
def main(client_class=None): global app if client_class is None: from thegame.gui.interactive import InteractiveClient client_class = InteractiveClient import sys from PyQt5.QtWidgets import QApplication from thegame.gui.scene import Scene from thegame.gui.view import View app = QApplication(sys.argv) scene = Scene() view = View(scene) client_instance = client_class() client_instance._attach(view, scene) client_instance.start() view.show() return app.exec()
def resizeEvent(self, event): global tab_6_size_indicator, total_till, browse_cnt, thumbnail_indicator global tab_6_player if (ui.tab_6.width() > 500 and tab_6_player == "False" and iconv_r != 1 and not ui.lock_process): #browse_cnt = 0 #if tab_6_size_indicator: # tab_6_size_indicator.pop() tab_6_size_indicator.append(ui.tab_6.width()) if not ui.scrollArea.isHidden(): print('--------resizing----') ui.next_page('not_deleted') QtWidgets.QApplication.processEvents() elif not ui.scrollArea1.isHidden(): ui.thumbnail_label_update() logger.debug('updating thumbnail window')
def main(): # This is required so that app.quit can be invoked when the quickview # is closed. If it is not present then the app does not exit. It is # possibly a bug in PyQt or Qt. global app app = QtWidgets.QApplication(sys.argv) quickview = QtQuick.QQuickView() if getattr(sys, 'frozen', None): basedir = sys._MEIPASS else: basedir = os.path.dirname(__file__) # The app dir is in the default import path but we can't put the QtQuick # import lib dirs there because of a name clash (on OSX) with the QtQuick # dll. print(("Qt5 Qml import paths: " \ + unicode(quickview.engine().importPathList()))) quickview.setSource(QtCore.QUrl('qrc:/hello.qml')) quickview.engine().quit.connect(app.quit) quickview.show() app.exec_()
def startup(css=None): # yea yea.... globals suck... global qapp # the main QApplication global guiq # queue of GUI calls to proxy global ethread # QtThread that consumes guiq global workerq # queue of "worker" calls to proxy guiq = e_threads.EnviQueue() workerq = e_threads.EnviQueue() currentThread().QtSafeThread = True qapp = VQApplication(sys.argv) if css: qapp.setStyleSheet(css) ethread = QEventThread(guiq) ethread.idleadd.connect(qapp.callFromQtLoop) ethread.start() workerThread()
def main(): app = QApplication(sys.argv) w = QMainWindow() central_widget = CentralWidget() my_widgets = [ (GoalWidget('one', '5'), 1, 1), (GoalWidget('two', '2'), 1, 2), (GoalWidget('An example of goal\nwith a long name', '3'), 2, 2), (GoalWidget('four', '1'), 2, 3), (GoalWidget('five', '4'), 3, 2), ] my_lines = [ (0, 2), (1, 2), (2, 4), (3, 4), ] for widget, row, column in my_widgets: central_widget.addCustomWidget(widget, row, column) for upper, lower in my_lines: central_widget.addCustomLine(upper, lower) w.setCentralWidget(central_widget) w.show() sys.exit(app.exec_())
def main(): application = QtWidgets.QApplication([]) window = QtWidgets.QWidget() layout_numbers = QtWidgets.QVBoxLayout(window) result = QtWidgets.QTextEdit() layout_numbers.addWidget(result) # Numbers from 0 to 9, Numeros de 0 a 9 for number in range(10): button = QtWidgets.QPushButton(str(number)) button.clicked.connect(lambda _, number=number: result.insertPlainText(str(number))) layout_numbers.addWidget(button) # Math Operators, Operadores Matematicos operators = QtWidgets.QWidget() layout_operators = QtWidgets.QHBoxLayout(operators) for operator in ("*", "/", "+", "-", "//"): button = QtWidgets.QPushButton(str(operator)) button.clicked.connect(lambda _, operator=operator: result.insertPlainText(str(operator))) layout_operators.addWidget(button) layout_numbers.addWidget(operators) # Solve the user input, Resolver lo ingresado por el usuario solve = QtWidgets.QPushButton("EVAL", window) solve.clicked.connect(lambda _, maths=result: result.setPlainText(str(eval(maths.toPlainText())))) layout_numbers.addWidget(solve) window.show() exit(application.exec_())
def __init__(self, document): """ Args: document (Document): """ super().__init__(None) # no brown object exists for this # TODO: make one self.document = document self.app = QtWidgets.QApplication([]) self.main_window = MainWindow() self.scene = QtWidgets.QGraphicsScene() self.view = self.main_window.graphicsView self.view.setScene(self.scene) self.registered_music_fonts = {} self.font_database = QtGui.QFontDatabase() ######## PUBLIC METHODS ########
def main(): # import qtmodern.styles # import qtmodern.windows import sys from PyQt5.QtWidgets import QApplication from PyQt5.QtCore import Qt, QLocale from .gui.main import MainWindow from silx.resources import register_resource_directory register_resource_directory('crispy', 'crispy.resources') QLocale.setDefault(QLocale.c()) app = QApplication(sys.argv) window = MainWindow() window.show() # qtmodern.styles.dark(app) # mw = qtmodern.windows.ModernWindow(window) # mw.show() app.setAttribute(Qt.AA_UseHighDpiPixmaps) sys.exit(app.exec_())
def start(self): """Display the GUI""" myApp = QApplication(sys.argv) myEngine = QQmlApplicationEngine() sys.excepthook = lambda typ, val, tb: self.error_handler(typ, val, tb) myEngine.rootContext().setContextProperty("python", self) # Need to set this before loading myEngine.load(QUrl(qml_file)) # These two are hacks, because getting them in the __init__ and RAII working isn't self.debug_window = ScrollableDialog() self.clipboard = myApp.clipboard() self.analyze_loadorder(None) sys.exit(myApp.exec_())
def quickModKeyAsk(self): modifiers = QtWidgets.QApplication.queryKeyboardModifiers() clickMode = 0 # basic mode if modifiers == QtCore.Qt.ControlModifier: clickMode = 1 # ctrl elif modifiers == QtCore.Qt.ShiftModifier: clickMode = 2 # shift elif modifiers == QtCore.Qt.AltModifier: clickMode = 3 # alt elif modifiers == QtCore.Qt.ControlModifier | QtCore.Qt.ShiftModifier | QtCore.Qt.AltModifier: clickMode = 4 # ctrl+shift+alt elif modifiers == QtCore.Qt.ControlModifier | QtCore.Qt.AltModifier: clickMode = 5 # ctrl+alt elif modifiers == QtCore.Qt.ControlModifier | QtCore.Qt.ShiftModifier: clickMode = 6 # ctrl+shift elif modifiers == QtCore.Qt.AltModifier | QtCore.Qt.ShiftModifier: clickMode = 7 # alt+shift return clickMode
def _item_doubleclicked(self, widget): """An item in the table was clicked.""" column = widget.column() row = widget.row() if column == self.media_col: # click in the media column, execute externally msg = self._messages[row] if msg.extfile_path is not None: logger.debug("Opening external file %r", msg.extfile_path) subprocess.call(['/usr/bin/xdg-open', msg.extfile_path]) elif column == self.text_col: # click in the text column, copy to clipboard clipboard = QtWidgets.QApplication.clipboard() clipboard.setText(widget.text())
def resizeEvent(self,event): global tab_6_size_indicator,total_till,browse_cnt,thumbnail_indicator global mpvplayer,tab_6_player if (ui.tab_6.width() > 500 and tab_6_player == "False" and iconv_r != 1 and not ui.lock_process): #browse_cnt = 0 if tab_6_size_indicator: tab_6_size_indicator.pop() tab_6_size_indicator.append(ui.tab_6.width()) if not ui.scrollArea.isHidden(): print('--------resizing----') ui.next_page('not_deleted') QtWidgets.QApplication.processEvents() elif not ui.scrollArea1.isHidden(): ui.thumbnail_label_update()
def started(self): global mpvplayer,epn,new_epn,epn_name_in_list,fullscr,mpv_start global Player,cur_label_num,epn_name_in_list,site if self.tab_5.isHidden() and thumbnail_indicator: length_1 = self.list2.count() q3="self.label_epn_"+str(length_1+cur_label_num)+".setText((self.epn_name_in_list))" exec(q3) q3="self.label_epn_"+str(length_1+cur_label_num)+".setAlignment(QtCore.Qt.AlignCenter)" exec(q3) QtWidgets.QApplication.processEvents() print("Process Started") print(mpvplayer.processId()) mpv_start =[] mpv_start[:]=[] t = "Loading: "+self.epn_name_in_list+" (Please Wait)" #print t self.progressEpn.setValue(0) self.progressEpn.setFormat((t)) if MainWindow.isFullScreen() and site!="Music": self.superGridLayout.setSpacing(0) self.gridLayout.setSpacing(0) self.frame1.show() if self.frame_timer.isActive(): self.frame_timer.stop()
def main(params, nb_cpu, nb_gpu, use_gpu, extension): logger = init_logging(params.logfile) logger = logging.getLogger('circus.merging') file_out_suff = params.get('data', 'file_out_suff') extension_in = extension extension_out = '-merged' if comm.rank == 0: if (extension != '') and (os.path.exists(file_out_suff + '.result%s.hdf5' %extension_out)): erase = query_yes_no("Export already made! Do you want to erase everything?", default=None) if erase: purge(file_out_suff, extension) extension_in = '' comm.Barrier() if comm.rank == 0: app = QApplication([]) try: pylab.style.use('ggplot') except Exception: pass else: app = None if comm.rank == 0: print_and_log(['Launching the merging GUI...'], 'debug', logger) mygui = gui.MergeWindow(params, app, extension_in, extension_out) sys.exit(app.exec_())
def startGUI(): app = QApplication(sys.argv) mw = GUIMainWindow() # cw = GUICenterWidget() rc = app.exec_() del app sys.exit(rc)
def startCameraGUI(): app = QApplication(sys.argv) mw = CameraMainWindow() # cw = CameraCenterWidget() rc = app.exec_() del app sys.exit(rc)
def startRGBSensorGUI(): app = QApplication(sys.argv) mw = RGBMainWindow() # cw = RGBCenterWidget() rc = app.exec_() del app sys.exit(rc)
def main(): # assumes unsigned byte datatype and volume dimensions of 256x256x225 volsize = (256, 256, 225) volume = load_raw(os.path.join("data", "head256.raw"), volsize) tff = load_transferfunction(os.path.join("data", "tff.dat")) app = QtWidgets.QApplication([]) window = QGLControllerWidget(volume, volsize, tff) window.move(QtWidgets.QDesktopWidget().rect().center() - window.rect().center()) window.show() app.exec_()
def qWait(msec): start = time.time() QtGui.QApplication.processEvents() while time.time() < start + msec * 0.001: QtGui.QApplication.processEvents()
def test_app (): app = QApplication(sys.argv) app.setObjectName ("testApplication") ex = TestApplication() ale = Ale (output="mouse.log", user="testUser", toolname="mousetest", toolversion="0.0.1") # install globally app.installEventFilter (ale) sys.exit (app.exec_())
def test_drag2 (): app = QApplication(sys.argv) ex = Example() ale = Ale (output="drag2.log", user="testUser", toolname="dragtest", toolversion="0.0.1") # install globally app.installEventFilter (ale) ex.show() app.exec_()
def test_close (): app = QApplication(sys.argv) ex = Example() ale = Ale () # install globally app.installEventFilter (ale) sys.exit(app.exec_())
def main(): """ Main function, staring GUI. """ version = pkg_resources.require("pytc-gui")[0].version try: app = QW.QApplication(sys.argv) app.setApplicationName("pytc") app.setApplicationVersion(version) pytc_run = MainWindow(app) sys.exit(app.exec_()) except KeyboardInterrupt: sys.exit()
def main(): app = QApplication(sys.argv) qtTranslator = QTranslator() qtTranslator.load('torrentbro_' + QLocale.system().name(), QLibraryInfo.location(QLibraryInfo.TranslationsPath)) app.installTranslator(qtTranslator) ex = Home() sys.exit(app.exec_())
def run_activity_browser(): qapp = QtWidgets.QApplication(sys.argv) application = Application() application.show() def exception_hook(*args): print(''.join(traceback.format_exception(*args))) sys.excepthook = exception_hook sys.exit(qapp.exec_())
def _process_entry_point(channel, iface_name): logger.info('Bus monitor process started with PID %r', os.getpid()) app = QApplication(sys.argv) # Inheriting args from the parent process def exit_if_should(): if RUNNING_ON_WINDOWS: return False else: return os.getppid() != PARENT_PID # Parent is dead exit_check_timer = QTimer() exit_check_timer.setSingleShot(False) exit_check_timer.timeout.connect(exit_if_should) exit_check_timer.start(2000) def get_frame(): received, obj = channel.receive_nonblocking() if received: if obj == IPC_COMMAND_STOP: logger.info('Bus monitor process has received a stop request, goodbye') app.exit(0) else: return obj win = BusMonitorWindow(get_frame, iface_name) win.show() logger.info('Bus monitor process %r initialized successfully, now starting the event loop', os.getpid()) sys.exit(app.exec_()) # TODO: Duplicates PlotterManager; refactor into an abstract process factory
def _process_entry_point(channel): logger.info('Plotter process started with PID %r', os.getpid()) app = QApplication(sys.argv) # Inheriting args from the parent process def exit_if_should(): if RUNNING_ON_WINDOWS: return False else: return os.getppid() != PARENT_PID # Parent is dead exit_check_timer = QTimer() exit_check_timer.setSingleShot(False) exit_check_timer.timeout.connect(exit_if_should) exit_check_timer.start(2000) def get_transfer(): received, obj = channel.receive_nonblocking() if received: if obj == IPC_COMMAND_STOP: logger.info('Plotter process has received a stop request, goodbye') app.exit(0) else: return obj win = PlotterWindow(get_transfer) win.show() logger.info('Plotter process %r initialized successfully, now starting the event loop', os.getpid()) sys.exit(app.exec_())
def main(): app = QtWidgets.QApplication(sys.argv) form = MainForm() form.show() app.exec_()
def main(): app = QtWidgets.QApplication( ['fred'] ) prog = QtWidgets.QProgressBar() prog.setMinimum( 0 ) prog.setMaximum( total ) prog.setTextVisible( False ) prog.setMinimumHeight( 50 ) prog.show() layout = QtWidgets.QHBoxLayout( prog ) label = QtWidgets.QLabel() layout.addWidget( label ) layout.setContentsMargins( 20, 0, 0, 0 ) def inc(): print( 'inc' ) global count if count == total: timer.stop() else: count += 1 prog.setValue( count ) def setProgresLabel( self ): label.setText( '%3d%%' % (100 * count / total) ) prog.valueChanged.connect( setProgresLabel ) timer = QtCore.QTimer() timer.setInterval( 250 ) timer.timeout.connect( inc ) timer.start() app.exec_()
def event( self, event ): self.debugLogApp( 'Wb_App.event() type() %r %s' % (event.type(), qt_event_type_names.get( event.type(), '-unknown-' )) ) return QtWidgets.QApplication.event( self, event )
def tree(self): with open(l('tree.txt'), 'r') as tree_file: for line in tree_file: self.plainTextEdit.insertPlainText(line) self.plainTextEdit.moveCursor(QtGui.QTextCursor.End) QtWidgets.QApplication.processEvents() self.plainTextEdit.appendPlainText("\n\n\n\nNo viruses, malware, trojans or spyware found. Your computer is clean.\n")
def mainPyQt4Youtube(): # ?????????import from PyQt4.QtCore import QUrl from PyQt4.QtGui import QApplication from PyQt4.QtWebKit import QWebView, QWebSettings from PyQt4.QtNetwork import QNetworkProxyFactory url = 'https://www.youtube.com/?hl=ja&gl=JP' app = QApplication(sys.argv) # Youtube???????????? QNetworkProxyFactory.setUseSystemConfiguration(True) QWebSettings.globalSettings().setAttribute(QWebSettings.PluginsEnabled, True) QWebSettings.globalSettings().setAttribute(QWebSettings.DnsPrefetchEnabled, True) QWebSettings.globalSettings().setAttribute(QWebSettings.JavascriptEnabled, True) QWebSettings.globalSettings().setAttribute(QWebSettings.OfflineStorageDatabaseEnabled, True) QWebSettings.globalSettings().setAttribute(QWebSettings.AutoLoadImages, True) QWebSettings.globalSettings().setAttribute(QWebSettings.LocalStorageEnabled, True) QWebSettings.globalSettings().setAttribute(QWebSettings.PrivateBrowsingEnabled, True) QWebSettings.globalSettings().setAttribute(QWebSettings.DeveloperExtrasEnabled, True) # QWebView???Web????? browser = QWebView() browser.load(QUrl(url)) browser.setEnabled(True) browser.show() sys.exit(app.exec_()) ## PyQt5??Web???????.
def main(): app = QApplication(sys.argv) app.setApplicationName("Kaptan") app.setOrganizationName("Kaptan") app.setApplicationVersion("5.0 Beta3") #app.setStyleSheet(open(join(dirPath, "data/libkaptan.qss").read()) locale = QLocale.system().name() translator = QTranslator(app) translator.load("/usr/share/kaptan/languages/kaptan_{}.qm".format(locale)) app.installTranslator(translator) kaptan = Kaptan() kaptan.show() app.exec_()
def sigint_handler(*args): """Handler for the SIGINT signal.""" sys.stderr.write('\r') if QW.QMessageBox.question(None, '', "Are you sure you want to quit?", QW.QMessageBox.Yes | QW.QMessageBox.No, QW.QMessageBox.No) == QW.QMessageBox.Yes: QW.QApplication.quit()
def test_directory_dialog(qtbot): #assert qt_api.QApplication.instance() is not None widget = about.About() widget.show() qtbot.addWidget(widget)