def __main__(): app = QApplication(sys.argv) QCoreApplication.setAttribute(Qt.AA_ShareOpenGLContexts) gui = ExerciseMainWindow() gui.show() app.exec_()
def setup_app(): QCoreApplication.setAttribute(Qt.AA_DisableHighDpiScaling) app = QApplication(sys.argv) splash = QSplashScreen() pixmap = QPixmap(os.path.join(QGRAIN_ROOT_PATH, "assets", "icon.png")) pixmap.setDevicePixelRatio(1.0) splash.setPixmap(pixmap) splash.show() create_necessary_folders() app.setWindowIcon(QIcon(pixmap)) app.setApplicationDisplayName(f"QGrain ({QGRAIN_VERSION})") app.setApplicationVersion(QGRAIN_VERSION) app.setStyle(QStyleFactory.create("Fusion")) app.setStyleSheet("""* {font-family:Arial,Helvetica,Tahoma,Verdana; color:#000000;background-color:#c4cbcf;alternate-background-color:#b2bbbe; selection-color:#ffffff;selection-background-color:#555f69}""") plt.style.use(["science", "no-latex"]) plt.set_cmap("tab10") plt.rcParams["axes.facecolor"] = "#c4cbcf" plt.rcParams["figure.facecolor"] = "#c4cbcf" plt.rcParams["savefig.dpi"] = 300.0 plt.rcParams["savefig.facecolor"] = "white" plt.rcParams["savefig.transparent"] = True plt.rcParams["figure.max_open_warning"] = False setup_language(app) setup_logging() return app, splash
def __init__(self): # TODO: 上传结算单 logger.info("start") QCoreApplication.setAttribute(Qt.AA_EnableHighDpiScaling) QCoreApplication.setAttribute(Qt.AA_UseHighDpiPixmaps) super(RQAmsHelper, self).__init__() self._ctp_controller = CtpController() self._ctp_controller.update_state_info.connect(self._update_account_state_info) self._ctp_controller.on_trades.connect(self._on_trades) self._persister = Persister() self._app = QApplication() self._main_window = MainWindow(self._persister) self._login_window = LoginWindow() self._create_account_window = CreateAccountWindow() self._modify_account_window = ModifyAccountWindow() self._login_window.login.connect(self._login) self._main_window.logout_button_pushed.connect(self._switch_to_login_window) self._main_window.create_button_pushed.connect(self._open_create_account_window) self._main_window.modify_button_pushed.connect(self._open_modify_account_window) self._main_window.connect_account.connect(self._connect_account) self._main_window.disconnect_account.connect(self._disconnect_account) self._modify_account_window.account_modified.connect(self._account_modified) self._create_account_window.account_created.connect(self._account_created) self._server_url = os.environ.get("RQAMS_URL", "https://www.ricequant.com") self._uploaded_exec_ids = set(self._persister.get_uploaded_exec_ids()) LoginExpiredException.after_msg_box_slot = self._switch_to_login_window
def entry_point(): QCoreApplication.setAttribute(Qt.AA_ShareOpenGLContexts) app = QApplication(sys.argv) app.setStyle("cleanlooks") timer_ui = os.path.join(package_directory, 'timer.ui') form = Form(timer_ui) print('start exit') sys.exit(app.exec_())
def main(): QCoreApplication.setAttribute(Qt.AA_ShareOpenGLContexts) app = QtWidgets.QApplication(sys.argv) widget = ClippyrWidget() widget.window.show() sys.exit(app.exec_())
def main(): sys.argv += ['--style', 'material'] app = QApplication(sys.argv) QApplication.setAttribute(Qt.AA_EnableHighDpiScaling) QCoreApplication.setAttribute(Qt.AA_UseHighDpiPixmaps) engine = QQmlApplicationEngine('main.qml') sys.exit(app.exec_())
def __init__(self, name="Default app name"): QObject.__init__(self) self.__file_dialog_event = Event() self.__filename_dialog = None self.__splash = None self.folder_dialog_spawn.connect(self.__on_folder_dialog) self.window_dialog_spawn.connect(self.__on_window) QCoreApplication.setAttribute(Qt.AA_EnableHighDpiScaling, True) self.__app = QApplication([]) self.__app.setApplicationName(name)
def main(): sys.argv += ['--style', 'material'] app = QApplication(sys.argv) QApplication.setAttribute(Qt.AA_EnableHighDpiScaling) QCoreApplication.setAttribute(Qt.AA_UseHighDpiPixmaps) qmlRegisterType(Map, 'Map', 1, 0, 'Map') qmlRegisterType(Bot, 'Bot', 1, 0, 'Bot') engine = QQmlApplicationEngine('main.qml') sys.exit(app.exec_())
def test_WebEngineView_findText_exists(self): QCoreApplication.setAttribute(Qt.AA_EnableHighDpiScaling) app = QApplication.instance() or QApplication() top_level = QWidget() layout = QVBoxLayout(top_level) self._view = QWebEngineView() self._view.loadFinished.connect(self.loaded) self._view.load(QUrl.fromLocalFile(os.path.join(TEST_DIR, "fox.html"))) self._view.setMinimumSize(QSize(400, 300)) self._callback_count = 0 layout.addWidget(self._view) top_level.show() app.exec_()
def main(): sys.argv += ['--style', 'material'] QGuiApplication.setAttribute(Qt.AA_EnableHighDpiScaling) QCoreApplication.setAttribute(Qt.AA_UseHighDpiPixmaps) QCoreApplication.setAttribute(Qt.AA_UseOpenGLES) app = QGuiApplication(sys.argv) engine = QQmlApplicationEngine() engine.load('Main.qml') if not engine.rootObjects(): sys.exit(-1) sys.exit(app.exec_())
def main(): # Kill the program when ctrl-c is used signal.signal(signal.SIGINT, signal.SIG_DFL) QCoreApplication.setAttribute(Qt.AA_ShareOpenGLContexts) QCoreApplication.setOrganizationName('hexrd') QCoreApplication.setApplicationName('hexrd') app = QApplication(sys.argv) window = MainWindow() window.ui.show() sys.exit(app.exec_())
def __init__(self): """App constructor""" self.streamingAPI = CHOSEN_STREAMING_API print(self.streamingAPI) QApplication.setAttribute(Qt.AA_EnableHighDpiScaling) sys_argv = sys.argv sys_argv += ['--style', 'fusion'] app = QApplication(sys_argv) QCoreApplication.setAttribute(Qt.AA_UseHighDpiPixmaps) # Set up the application window pwd = os.path.dirname(__file__) qmlDir = os.path.join(pwd, "UIPkg") self.engine = QmlInstantEngine() self.engine.addFilesFromDirectory(qmlDir, recursive=True) self.engine.setWatching( os.environ.get("MESHROOM_INSTANT_CODING", False)) # whether to output qml warnings to stderr (disable by default) self.engine.setOutputWarningsToStandardError( MessageHandler.outputQmlWarnings) qInstallMessageHandler(MessageHandler.handler) ctx = self.engine.rootContext() # Create a Backend object to communicate with QML self.backend = Backend() ctx.setContextProperty("backend", self.backend) ctx.setContextProperty("preview", self.backend.preview) ctx.setContextProperty("acquisition", self.backend.acquisition) self.engine.addImageProvider("imageProvider", self.backend.preview.imageProvider) # Apply palette darkPalette = Palette(self.engine) # Run app self.engine.load("UIPkg/App.qml") sys.exit(app.exec_())
def main() -> None: """""" kill_subprocess() freeze_support() QCoreApplication.setAttribute(Qt.AA_ShareOpenGLContexts) app = QApplication(sys.argv) app.processEvents() app.setQuitOnLastWindowClosed(False) app.lastWindowClosed.connect(kill_subprocess) app.lastWindowClosed.connect(kill_childs) app.lastWindowClosed.connect(lambda: app.quit()) os.environ['BCISTREAM_DPI'] = str(app.screens()[0].physicalDotsPerInch()) extra = {'danger': '#dc3545', 'warning': '#e2a963', 'success': '#17a2b8', 'font_family': 'Roboto', 'font_size': 'unset', } if ConfigManager().get('framework', 'theme', 'light') == 'light': apply_stylesheet(app, theme='light_cyan_500.xml', invert_secondary=True, extra=extra, parent='bci_framework_qt_material') else: apply_stylesheet(app, theme='dark_cyan.xml', extra=extra, parent='bci_framework_qt_material') stylesheet = app.styleSheet() with open(os.path.join(os.path.dirname(__file__), 'custom.css')) as file: app.setStyleSheet(stylesheet + file.read().format(**os.environ)) generate_icons() frame = BCIFramework() frame.main.showMaximized() app.exec_()
def __gui_initialization(args: "argparse.Namespace"): """Performs all the initialization of the GUI components. Args: args: App configuration namespace.""" # State the signals handled by this application signal.signal(signal.SIGINT, signal.SIG_DFL) # Necessary for Qt Web Engine from PySide2.QtCore import Qt, QCoreApplication QCoreApplication.setAttribute(Qt.AA_ShareOpenGLContexts) # Initialize PySide2 from PySide2.QtWidgets import QApplication app = QApplication() app.setApplicationName("dial") app.aboutToQuit.connect(exit_application) from dial_gui.project import ProjectManagerGUISingleton __plugins_initialization(args)
def main(): # Kill the program when ctrl-c is used signal.signal(signal.SIGINT, signal.SIG_DFL) QCoreApplication.setAttribute(Qt.AA_ShareOpenGLContexts) QCoreApplication.setOrganizationName('hexrd') QCoreApplication.setApplicationName('hexrd') app = QApplication(sys.argv) data = resource_loader.load_resource(hexrd.ui.resources.icons, 'hexrd.ico', binary=True) pixmap = QPixmap() pixmap.loadFromData(data, 'ico') icon = QIcon(pixmap) app.setWindowIcon(icon) window = MainWindow() window.set_icon(icon) window.show() sys.exit(app.exec_())
def main(): # Settings QCoreApplication.setAttribute( Qt.AA_EnableHighDpiScaling) # DOESN'T WORK, USE SCRIPT INSTEAD QCoreApplication.setAttribute(Qt.AA_UseDesktopOpenGL, True) # Paths app_name = CONFIG['tool']['poetry']['name'] current_path = os.path.dirname(sys.argv[0]) package_path = os.path.join(current_path, f'{app_name}App') if not os.path.exists(package_path): package_path = current_path main_qml_path = QUrl.fromLocalFile( os.path.join(package_path, 'Gui', 'main.qml')) gui_path = str(QUrl.fromLocalFile(package_path).toString()) easyAppGui_path = os.path.join(easyAppGui.__path__[0], '..') home_path = pathlib.Path.home() settings_path = str(home_path.joinpath(f'.{app_name}', 'settings.ini')) languages = CONFIG['ci']['app']['translations']['languages'] translations_dir = CONFIG['ci']['app']['translations']['dir'] translations_path = os.path.join(package_path, *translations_dir.split('/')) # QtWebEngine QtWebEngine.initialize() # Application app = App(sys.argv) app.setApplicationName(CONFIG['tool']['poetry']['name']) app.setApplicationVersion(CONFIG['tool']['poetry']['version']) app.setOrganizationName(CONFIG['tool']['poetry']['name']) app.setOrganizationDomain(CONFIG['tool']['poetry']['name']) # QML application engine engine = QQmlApplicationEngine() # Python objects to be exposed to QML py_qml_proxy_obj = PyQmlProxy() translator = Translator(app, engine, translations_path, languages) vtk_handler = VtkCanvasHandler() # Expose the Python objects to QML engine.rootContext().setContextProperty('_pyQmlProxyObj', py_qml_proxy_obj) engine.rootContext().setContextProperty('_settingsPath', settings_path) engine.rootContext().setContextProperty('_translator', translator) engine.rootContext().setContextProperty('_vtkHandler', vtk_handler) engine.rootContext().setContextProperty('_projectConfig', CONFIG) engine.rootContext().setContextProperty('_isTestMode', isTestMode()) # Register types to be instantiated in QML qmlRegisterType(FigureCanvasQtQuickAgg, 'MatplotlibBackend', 1, 0, 'FigureCanvas') qmlRegisterType(FboItem, 'QtVTK', 1, 0, 'VtkFboItem') # Add paths to search for installed modules engine.addImportPath(easyAppGui_path) engine.addImportPath(gui_path) # Load the root QML file engine.load(main_qml_path) # Root application window root_window = engine.rootObjects()[0] # VTK setup app.vtkSetup(root_window) vtk_handler.fbo = app._m_vtkFboItem vtk_handler.context = root_window py_qml_proxy_obj.setVtkHandler(vtk_handler) # Customize app window titlebar if platform.system() == "Darwin": import ctypes, objc, Cocoa ptr = int(root_window.winId()) view = objc.objc_object(c_void_p=ctypes.c_void_p(ptr)) window = view._.window window.setStyleMask_(window.styleMask() | Cocoa.NSFullSizeContentViewWindowMask) window.setTitlebarAppearsTransparent_(True) window.setTitleVisibility_(Cocoa.NSWindowTitleHidden) # Event loop if not engine.rootObjects(): sys.exit(-1) sys.exit(app.exec_())
def main(): """main function """ # Adds Ctrl+C support to kill app signal.signal(signal.SIGINT, signal.SIG_DFL) QCoreApplication.setAttribute(Qt.AA_ShareOpenGLContexts) app = QApplication(sys.argv) app.setOrganizationName("djieffx") app.setApplicationName("vspleeter") loader = QUiLoader() mw = loader.load(os.path.join(os.path.dirname(__file__), "vspleeter_mainWindow.ui")) def getBinaries(): """Create a generator that yield the proper command name if the checkbox is checked. :return: generator with command name :rtype: generator """ if mw.cpuCheckBox.checkState(): yield 'spleeter' if mw.gpuCheckBox.checkState(): yield 'spleeter-gpu' def getStemsAmount(): """Create a generator that yield the stems amount if the checkbox is checked. :return: generator with stem count :rtype: generator """ if mw.stems2CheckBox.checkState(): yield '2' if mw.stems4CheckBox.checkState(): yield '4' if mw.stems5CheckBox.checkState(): yield '5' def createOutputDir(cmdSpecs): """Create the output directory from defined output specifications :param cmdSpecs: context based variables to execute spleeter command :type cmdSpecs: dict :return: the output directory :rtype: str """ outputDir = OUTPUT_PATH_SUFFIX.format(**cmdSpecs) if not os.path.exists(outputDir): os.makedirs(outputDir, mode=0o777) print('Created the {0} directory'.format(outputDir)) return outputDir def generateCommandsPerElements(binaryGenerator, inputFilePath, stemsCPUGenerator, stemsGPUGenerator, rootOutputDir): """Generate all the commands necessary, per what is selected in the UI, looping on the process type :param binaryGenerator: generator with all the binary selections :param str inputFilePath: The file to be spleeted :param stemsCPUGenerator: generator with the CPU processes flag :param stemsGPUGenerator: generator with the GPU processes flag :param str rootOutputDir: The output directory :return: generator with all command line to spleet the file """ for binaryName in binaryGenerator: cmdSpecs = { 'rootOutputDir': rootOutputDir, 'basename': os.path.basename(os.path.splitext(inputFilePath)[0]), 'binaryType': 'CPU', 'binaryName': binaryName, 'inputFilePath': inputFilePath, 'stemsGenerator': stemsCPUGenerator } if 'gpu' in binaryName: cmdSpecs['binaryType'] = 'GPU' cmdSpecs['stemsGenerator'] = stemsGPUGenerator yield from generateCmdPerStem(cmdSpecs) else: yield from generateCmdPerStem(cmdSpecs) def generateCmdPerStem(cmdSpecs): """Generate the command from the stem count :param dict cmdSpecs: a dictionary containing all necessary data to generate the command :return: a command to execute :rtype: list """ stemsGenerator = cmdSpecs['stemsGenerator'] for stemNum in stemsGenerator: cmdSpecs['stemNum'] = stemNum outputDir = createOutputDir(cmdSpecs) if os.name == 'nt': cmd = [ "python", "-m", "{}".format(cmdSpecs['binaryName']), "separate", "-i", "{}".format(cmdSpecs['inputFilePath']), "-p", "spleeter:{}stems".format(cmdSpecs['stemNum']), "-o", "{}".format(outputDir) ] else: cmd = [ "{}".format(cmdSpecs['binaryName']), "separate", "-i", "{}".format(cmdSpecs['inputFilePath']), "-p", "spleeter:{}stems".format(cmdSpecs['stemNum']), "-o", "{}".format(outputDir) ] yield cmd def browseForInputFile(_): """Opens a file browser, and set the input file :param _: unused """ inputFile = QFileDialog.getOpenFileName()[0] mw.inputFileLineEdit.setText(inputFile) checkToEnableProcess() def browseForOutputDir(_): """Opens a file browser, and set the input file :param _: unused """ outputDir = QFileDialog.getExistingDirectory() mw.outputDirLineEdit.setText(outputDir) checkToEnableProcess() def checkToEnableProcess(): """If all the necessary params are set, enable the process button""" mw.processPushButton.setEnabled(False) inputFileCheck = bool(mw.inputFileLineEdit.text()) procCheck = any( [ mw.cpuCheckBox.checkState(), mw.gpuCheckBox.checkState(), ] ) stemsCheck = any( [ mw.stems2CheckBox.checkState(), mw.stems4CheckBox.checkState(), mw.stems5CheckBox.checkState(), ] ) outputFileCheck = bool(mw.outputDirLineEdit.text()) if all( [ inputFileCheck, procCheck, stemsCheck, outputFileCheck, ] ): mw.processPushButton.setEnabled(True) def processBatchElements(_): """Process all the data from the UI, and execute all the commands generated :param _: unused input """ binaryGenerator = getBinaries() inputFilePath = mw.inputFileLineEdit.text() stemsCPUGenerator = getStemsAmount() stemsCPUGenerator, stemsGPUGenerator = itertools.tee(stemsCPUGenerator) rootOutputDir = mw.outputDirLineEdit.text() generatedCmds = generateCommandsPerElements( binaryGenerator, inputFilePath, stemsCPUGenerator, stemsGPUGenerator, rootOutputDir ) generatedCmds, generatedCmdsForLength = itertools.tee(generatedCmds) amountOfCommands = 0 for _ in generatedCmdsForLength: amountOfCommands += 1 mw.progressBar.setRange(0, amountOfCommands) mw.progressBar.setValue(0) mw.resultTextEdit.setText('') mw.resultTextEdit.append('Source File: %s' % inputFilePath) for cmd in generatedCmds: currentJobCount = mw.progressBar.value() subprocess.run(cmd) mw.progressBar.setValue(currentJobCount + 1) mw.resultTextEdit.append('Output %s:' % cmd[5].split(':')[1]) outputFiles = glob.glob(os.path.join(cmd[7], '*', '*')) for outputFile in outputFiles: mw.resultTextEdit.append(outputFile) mw.resultTextEdit.append('') checkToEnableProcess() mw.inputFilePushButton.clicked.connect(browseForInputFile) mw.outputDirPushButton.clicked.connect(browseForOutputDir) mw.cpuCheckBox.stateChanged.connect(checkToEnableProcess) mw.gpuCheckBox.stateChanged.connect(checkToEnableProcess) mw.stems2CheckBox.stateChanged.connect(checkToEnableProcess) mw.stems4CheckBox.stateChanged.connect(checkToEnableProcess) mw.stems5CheckBox.stateChanged.connect(checkToEnableProcess) mw.processPushButton.clicked.connect(processBatchElements) mw.actionexit.triggered.connect(app.quit) mw.show() sys.exit(app.exec_())
def run_plugin_gui(): QCoreApplication.setAttribute(Qt.AA_ShareOpenGLContexts) app = QApplication(sys.argv) window = MainWindow() window.show() sys.exit(app.exec_())
# GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import os #from PyQt5 import QtCore from PySide2 import QtCore #from PyQt5.QtNetwork import QNetworkCookieJar, QNetworkCookie from PySide2.QtNetwork import QNetworkCookieJar, QNetworkCookie #from PyQt5.QtCore import QCoreApplication, QEvent from PySide2.QtCore import QCoreApplication, QEvent, Signal #from PyQt5.QtNetwork import QNetworkProxy from PySide2.QtNetwork import QNetworkProxy if os.name == 'posix': QCoreApplication.setAttribute(QtCore.Qt.AA_X11InitThreads, True) #from PyQt5.QtWebKitWidgets import QWebView, QWebPage from PySide2.QtWebEngineWidgets import QWebEngineView, QWebEnginePage #from PySide2 import QtWebEngineWidgets #from PyQt5.QtWebEngineWidgets import QWebView, QWebPage #from PyQt5.QtWebKit import QWebSettings #from PyQt5.QtWebEngineWidgets import QWebEnginePage #from PyQt5.QtWidgets import QApplication from PySide2.QtWidgets import QApplication #from PyQt5.QtCore import QUrl, Qt from PySide2.QtCore import QUrl, Qt #from PyQt5 import QtGui from PySide2 import QtGui import time import os
self.menuFromJpMeasure.triggered.connect( lambda: self.widgetSetup("fromjpmeasure")) self.btnToJpMeasure.clicked.connect( lambda: self.widgetSetup("tojpmeasure")) self.menuToJpMeasure.triggered.connect( lambda: self.widgetSetup("tojpmeasure")) self.btnFromJpYear.clicked.connect( lambda: self.widgetSetup("fromjpyear")) self.menuFromJpYear.triggered.connect( lambda: self.widgetSetup("fromjpyear")) self.menuFromJpYearHistoric.triggered.connect( lambda: self.widgetSetup("fromjpyearhistoric")) self.btnToJpYear.clicked.connect(lambda: self.widgetSetup("tojpyear")) self.menuToJpYear.triggered.connect( lambda: self.widgetSetup("tojpyear")) self.btnZodiac.clicked.connect(lambda: self.widgetSetup("zodiac")) self.menuZodiac.triggered.connect(lambda: self.widgetSetup("zodiac")) def exitHandler(self): app.exit() if __name__ == '__main__': QCoreApplication.setAttribute( Qt.AA_ShareOpenGLContexts ) # suppresses error message on laptop python console app = QApplication(sys.argv) #form = Form(theUIFileName) window = MainWindow(theUIFileName, devMode) sys.exit(app.exec_())
def start(): QCoreApplication.setAttribute(Qt.AA_ShareOpenGLContexts) app = QApplication() form = Form( os.path.join(pathlib.Path(__file__).parent.absolute(), "form.ui")) sys.exit(app.exec_())
def start_management(filepath=None, use_daemon=None, profiling=False): if sys.platform == "darwin": macos_bigsur_wants_layer() if not check_dependencies_qt(): # it's likely that other dependencies are also missing. check them here before exiting. check_dependencies() sys.exit(1) set_app_user_model_id() set_windows_event_loop_policy() from PySide2.QtWidgets import QApplication, QSplashScreen, QMessageBox from PySide2.QtGui import QFontDatabase, QPixmap, QIcon from PySide2.QtCore import Qt, QCoreApplication from .config import FONT_LOCATION, IMG_LOCATION, Conf # Enable High-DPI support # https://stackoverflow.com/questions/35714837/how-to-get-sharp-ui-on-high-dpi-with-qt-5-6 if ("QT_DEVICE_PIXEL_RATIO" not in os.environ and "QT_AUTO_SCREEN_SCALE_FACTOR" not in os.environ and "QT_SCALE_FACTOR" not in os.environ and "QT_SCREEN_SCALE_FACTORS" not in os.environ): QCoreApplication.setAttribute(Qt.AA_EnableHighDpiScaling) # No more rounding # https://github.com/pyqtgraph/pyqtgraph/issues/756 # https://lists.qt-project.org/pipermail/development/2019-September/037434.html QApplication.setHighDpiScaleFactorRoundingPolicy( Qt.HighDpiScaleFactorRoundingPolicy.PassThrough) # Use highDPI pixmaps QApplication.setAttribute(Qt.AA_UseHighDpiPixmaps) app = QApplication(sys.argv) app.setApplicationDisplayName("angr management") app.setApplicationName("angr management") icon_location = os.path.join(IMG_LOCATION, 'angr.png') QApplication.setWindowIcon(QIcon(icon_location)) # try to import the initial configuration for the install Conf.attempt_importing_initial_config() # Make + display splash screen splashscreen_location = os.path.join(IMG_LOCATION, 'angr-splash.png') splash_pixmap = QPixmap(splashscreen_location) splash = QSplashScreen(splash_pixmap, Qt.WindowStaysOnTopHint) icon_location = os.path.join(IMG_LOCATION, 'angr.png') splash.setWindowIcon(QIcon(icon_location)) splash.setWindowFlags(Qt.WindowStaysOnTopHint | Qt.FramelessWindowHint) splash.setEnabled(False) splash.show() for _ in range(5): time.sleep(0.01) app.processEvents() if not check_dependencies(): sys.exit(1) from .ui.css import refresh_theme # import .ui after shwing the splash screen since it's going to take time refresh_theme() import angr angr.loggers.profiling_enabled = True if profiling else False from .logic import GlobalInfo from .ui.main_window import MainWindow # Load fonts QFontDatabase.addApplicationFont( os.path.join(FONT_LOCATION, "SourceCodePro-Regular.ttf")) QFontDatabase.addApplicationFont( os.path.join(FONT_LOCATION, "DejaVuSansMono.ttf")) # Initialize font-related configuration Conf.init_font_config() # Set global font app.setFont(Conf.ui_default_font) GlobalInfo.gui_thread = threading.get_ident() file_to_open = filepath if filepath else None main_window = MainWindow(app=app, use_daemon=use_daemon) splash.finish(main_window) if file_to_open is not None: main_window.load_file(file_to_open) app.exec_()
def main(): logic = Logic() # Serial to Arduino # serial_reader = SerialReader() serial_reader = SerialReader() while not serial_reader.isOpen: serial_reader.try_open() # TCP Server to rPi tcp_server = TCP_Server() tcp_server.catch_client() QCoreApplication.setAttribute(Qt.AA_ShareOpenGLContexts) app = QApplication([]) window = TseMainWindow() # logika serial_reader.signals.message.connect(window.parse_incoming_message) serial_reader.signals.message.connect(logic.update) # przyciski HOME window.ui.btn_homing.clicked.connect(window.prepare_message_homing) window.ui.btn_homing_ack.clicked.connect( lambda x: serial_reader.write("9")) window.signals.sendSerial.connect(serial_reader.write) # from GUI dx dy to cal logic window.signals.sliderPosOrient.connect(logic.slider_pos_orient) # from logic to update sliders with wanted pos logic.signals.setUserSliderValues.connect(window.update_user_sliders) # apexes from logic to gui update logic.signals.setCurrentPosOrient.connect(window.update_current_posorient) logic.signals.setWantedPosOrient.connect(window.update_wanted_posorient) # task sending window.ui.btn_task.clicked.connect(window.prepare_message_task) # tcp camera message -> gui update tcp_server.signals.message_camera.connect(window.update_camera_target_info) # tcp imu message -> gui update tcp_server.signals.message_imu.connect(window.update_imu_label) # logic to dx dy ... predictions tcp_server.signals.message_camera.connect( logic.get_dposorient_to_follow_target) logic.signals.setFollowedUserSliders.connect( window.update_target_follow_derivatives) # timers interruptions, send task to TSE when enable window.send_task_timer.timeout.connect(window.prepare_message_task) # handle test pos button and set slider to zero button window.ui.btn_autosend.clicked.connect(window.send_task_timer_callback) window.ui.btn_test_pos.clicked.connect(window.set_sliders_to_test) window.ui.btn_zero.clicked.connect(window.set_d_sliders_to_zero) # loop button callback window.ui.btn_loop.clicked.connect(window.loop_button_callback) # log to file button callback window.ui.btn_log_to_file.clicked.connect(window.log_to_file_callback) # stabilize button enabled # window.ui.btn_stabilize.clicked.connect(window.stabilize_callback) #threading Serial and TCP thread = threading.Thread(target=serial_reader.loop, daemon=True) thread.start() thread2 = threading.Thread(target=tcp_server.loop, daemon=True) thread2.start() app.aboutToQuit.connect(lambda: serial_reader.stop()) app.aboutToQuit.connect(lambda: tcp_server.stop()) app.exec_()
def disable_opengl(): # Disable GPU acceleration # https://codereview.qt-project.org/c/qt/qtwebengine-chromium/+/206307 QCoreApplication.setAttribute(Qt.AA_UseSoftwareOpenGL, True)
self.__ui = ui def __load_ui(self, parent): loader = QUiLoader() path = os.path.join(os.path.dirname(__file__), "q3d_bars.ui") ui_file = QFile(path) ui_file.open(QFile.ReadOnly) ui = loader.load(ui_file, parent) ui_file.close() return ui def init_resize(self): fs = self.__ui.widget.frameSize() self.container.resize(fs) def resizeEvent(self, event): super().resizeEvent(event) fs = self.__ui.widget.frameSize() self.container.resize(fs) if __name__ == "__main__": from PySide2.QtCore import QCoreApplication QCoreApplication.setAttribute(Qt.AA_ShareOpenGLContexts) app = QApplication([]) widget = GapFillHeatMap() widget.show() widget.init_resize() sys.exit(app.exec_())
def addToPlaylist(self, index): self.m_appLogic.AddToPlaylist(index, self.m_selectedIndex) if __name__ == '__main__': sys.argv += ['--style', 'material'] QApplication.setAttribute(Qt.AA_EnableHighDpiScaling) app = QApplication(sys.argv) fdb = QFontDatabase() fdb.addApplicationFont("fonts/FiraSans-Regular.ttf") appFont = QFont("Fira Sans") app.setFont(appFont) QCoreApplication.setAttribute(Qt.AA_UseHighDpiPixmaps) engine = QQmlApplicationEngine() # Expose the list to the Qml code listViewModel = QStringListModel() playlistListViewModel = QStringListModel() appLogic = AppLogic(listViewModel, playlistListViewModel) backend = Backend(appLogic) appLogic.LoadArtists() engine.rootContext().setContextProperty("listViewModel", listViewModel) engine.rootContext().setContextProperty("playlistListViewModel", playlistListViewModel) engine.rootContext().setContextProperty("backend", backend)
import os, sys from PySide2.QtCore import QUrl, Qt, QCoreApplication from PySide2.QtWidgets import QApplication from PySide2.QtQml import QQmlApplicationEngine from PySide2.QtWebEngine import QtWebEngine if __name__ == '__main__': QCoreApplication.setAttribute(Qt.AA_EnableHighDpiScaling) app = QApplication(sys.argv) app.setOrganizationName("ESS") app.setOrganizationDomain("esss.se") app.setApplicationName("easyDiffraction") QtWebEngine.initialize() engine = QQmlApplicationEngine() engine.addImportPath(os.path.join(os.path.dirname(sys.argv[0]), "..", "Qml", "Imports")) engine.load(QUrl.fromLocalFile(os.path.join(os.path.dirname(sys.argv[0]), "..", "Qml", "main.qml"))) if not engine.rootObjects(): sys.exit(-1) sys.exit(app.exec_())
def main(): # pylint: disable=too-many-statements """main application function""" # Adds Ctrl+C support to kill app signal.signal(signal.SIGINT, signal.SIG_DFL) env_ocio = os.environ.get("OCIO") env_sequence = os.environ.get("SEQ") env_shot = os.environ.get("SHOT") QCoreApplication.setAttribute(Qt.AA_ShareOpenGLContexts) app = QApplication(sys.argv) app.setOrganizationName("djieffx") app.setApplicationName("ocio-lut-prescription") loader = QUiLoader() main_window = loader.load( os.path.join(os.path.dirname(__file__), "ui", "main_window.ui") ) main_window.setWindowTitle("ocio-lut-prescription") main_window.setWindowIcon(QIcon(":/icons/icon.png")) main_window.iccWhitePointLineEdit.setValidator(QIntValidator(1, 10000)) settings = QSettings() if env_ocio: main_window.ocioCfgLineEdit.setText(env_ocio) main_window.ocioSeqLineEdit.setText(env_sequence) main_window.ocioShotLineEdit.setText(env_shot) ui.load_ocio_config(main_window, settings) else: ui.load_settings(app, settings, main_window) @contextmanager def ocio_context(): """Keep current ocio context in memory, in case values are overriden in the UI""" sequence_context = main_window.ocioSeqLineEdit.text() shot_context = main_window.ocioShotLineEdit.text() if sequence_context: os.environ["SEQ"] = sequence_context if shot_context: os.environ["SHOT"] = shot_context yield if sequence_context: if env_sequence is None: del os.environ["SEQ"] else: os.environ["SEQ"] = env_sequence if shot_context: if env_shot is None: del os.environ["SHOT"] else: os.environ["SHOT"] = env_shot def with_ocio_context(): """decorator which allows running functions in an ocio context""" def decorator(func): @wraps(func) def wrapper(*args, **kwargs): with ocio_context(): return func(*args, **kwargs) return wrapper return decorator @with_ocio_context() def process_bake_lut(): """from the UI, generate a valid ociobakelut command, and execute it""" bake_cmd_data = ui.BakeCmdData(*ui.get_bake_cmd_data(main_window)) lut_name_param = {"lut_filename": core.get_lut_filename(bake_cmd_data)} bake_cmd_data = replace(bake_cmd_data, **lut_name_param) ociobakelut_cmd = core.get_ociobakelut_cmd(bake_cmd_data) process = subprocess.Popen( ociobakelut_cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE ) _, stderr = process.communicate() if process.returncode: main_window.resultLineEdit.setText("Error") main_window.resultLogTextEdit.setText(stderr.decode("utf-8")) else: main_window.resultLineEdit.setText(bake_cmd_data.lut_filename) stringed_log = core.ocio_report(bake_cmd_data, ociobakelut_cmd) main_window.resultLogTextEdit.setText(stringed_log) main_window.ocioCfgLoadPushButton.clicked.connect( lambda x: ui.browse_for_ocio_config(main_window, settings) ) main_window.outputDirBrowsePushButton.clicked.connect( lambda x: ui.browse_for_lut_output_dir(main_window, settings) ) main_window.ocioCfgLineEdit.textChanged.connect( lambda x: ui.load_ocio_config(main_window, settings) ) main_window.outputDirLineEdit.textChanged.connect( lambda x: ui.check_to_enable_baking(main_window) ) main_window.outputDirLineEdit.textChanged.connect( lambda x: ui.save_settings(settings, main_window) ) main_window.inputColorSpacesComboBox.currentIndexChanged.connect( lambda x: ui.save_settings(settings, main_window) ) main_window.outputColorSpacesComboBox.currentIndexChanged.connect( lambda x: ui.save_settings(settings, main_window) ) main_window.shaperColorSpacesComboBox.currentIndexChanged.connect( lambda x: ui.save_settings(settings, main_window) ) main_window.looksComboBox.currentIndexChanged.connect( lambda x: ui.save_settings(settings, main_window) ) main_window.lutFormatComboBox.currentIndexChanged.connect( lambda x: ui.save_settings(settings, main_window) ) main_window.lutFormatComboBox.currentIndexChanged.connect( lambda x: ui.check_for_icc( main_window, main_window.lutFormatComboBox.currentText() ) ) main_window.cubeSizeComboBox.currentIndexChanged.connect( lambda x: ui.save_settings(settings, main_window) ) main_window.shaperSizeComboBox.currentIndexChanged.connect( lambda x: ui.save_settings(settings, main_window) ) main_window.iccWhitePointLineEdit.textChanged.connect( lambda x: ui.save_settings(settings, main_window) ) main_window.iccDisplaysComboBox.currentIndexChanged.connect( lambda x: ui.save_settings(settings, main_window) ) main_window.iccDescriptionLineEdit.textChanged.connect( lambda x: ui.save_settings(settings, main_window) ) main_window.iccCopyrightLineEdit.textChanged.connect( lambda x: ui.save_settings(settings, main_window) ) main_window.actionSetDarkStyle.triggered.connect( lambda x: ui.set_dark_style(app, settings) ) main_window.actionSetSystemStyle.triggered.connect( lambda x: ui.set_system_style(app, settings) ) main_window.actionSettingsClear.triggered.connect( lambda x: ui.settings_clear(app, settings, main_window) ) main_window.processBakeLutPushButton.clicked.connect(process_bake_lut) main_window.show() sys.exit(app.exec_())
container = QWidget.createWindowContainer(self.renderWindow) container.setMinimumSize(QSize(400, 400)) hBoxLayout.addWidget(container) def updateDescription(self): text = "{}\n\nPython {}\n\n{}".format(QLibraryInfo.build(), sys.version, self.renderWindow.glInfo()) self.plainTextEdit.setPlainText(text) if __name__ == '__main__': parser = ArgumentParser(description="contextinfo", formatter_class=RawTextHelpFormatter) parser.add_argument('--gles', '-g', action='store_true', help='Use OpenGL ES') parser.add_argument('--software', '-s', action='store_true', help='Use Software OpenGL') parser.add_argument('--desktop', '-d', action='store_true', help='Use Desktop OpenGL') options = parser.parse_args() if options.gles: QCoreApplication.setAttribute(Qt.AA_UseOpenGLES) elif options.software: QCoreApplication.setAttribute(Qt.AA_UseSoftwareOpenGL) elif options.desktop: QCoreApplication.setAttribute(Qt.AA_UseDesktopOpenGL) app = QApplication(sys.argv) mainWindow = MainWindow() mainWindow.show() mainWindow.updateDescription() sys.exit(app.exec_())
def __init__(self, title="", icon="", web_contents="", debug=False, transparent=False, online=False, disable_gpu=False, url_rules="", cookies_path="", user_agent="", custom_css="", custom_js="", toolbar=""): """ * JWebApp(args) * :arg title:str: Required * :arg icon:str: Optional * :arg web_contents:str: Required * :arg debug:bool: Optional * :arg transparent:bool: Optional * :arg online:bool: Optional * :arg disable_gpu:bool: Optional * :arg url_rules:dict: Optional * :arg cookies_path:str: Optional * :arg user_agent:str: Optional * :arg custom_css:str: Optional * :arg custom_js:str: Optional * :arg toolbar:dict: Optional """ QCoreApplication.setAttribute(Qt.AA_UseHighDpiPixmaps, True) QCoreApplication.setAttribute(Qt.AA_EnableHighDpiScaling, True) if debug or "--dev" in sys.argv: # Adding some command line arguments for testing purposes, # this MUST BE done before initializing QApplication sys.argv.append("--remote-debugging-port=8000") print("Debugging Mode On") if not debug: debug = True else: print("Production Mode On, use (--dev) for debugging") # Enable/Disable GPU acceleration if not disable_gpu: # Virtual machine detection using SystemD detect_virtual_machine = subprocess.Popen(["systemd-detect-virt"], stdout=subprocess.PIPE, stderr=subprocess.STDOUT) # FIXME find a more reliable way of detecting NVIDIA cards detect_nvidia_pci = subprocess.Popen( "lspci | grep -i --color 'vga\|3d\|2d'", stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True) virtual = detect_virtual_machine.communicate() nvidia_pci = detect_nvidia_pci.communicate() nvidia_pci = nvidia_pci[0].decode("utf-8").lower() def disable_opengl(): # Disable GPU acceleration # https://codereview.qt-project.org/c/qt/qtwebengine-chromium/+/206307 QCoreApplication.setAttribute(Qt.AA_UseSoftwareOpenGL, True) if disable_gpu: disable_opengl() print("Disabling GPU, Software Rendering explicitly activated") else: if virtual[-1]: # Detect virtual machine print(f"Virtual machine detected:{virtual}") disable_opengl() elif nvidia_pci: # Detect NVIDIA cards if "nvidia" in nvidia_pci: print( "NVIDIA detected:Known bug - kernel rejected pushbuf") print("Falling back to Software Rendering") disable_opengl() else: print(f"Virtual Machine:{virtual[-1]}") super(JWebApp, self).__init__(sys.argv) self.title = title self.web_contents = web_contents self.debug = debug self.transparent = transparent self.online = online self.url_rules = url_rules self.cookies_path = cookies_path self.user_agent = user_agent self.custom_css = custom_css self.custom_js = custom_js self.icon = icon self.toolbar = toolbar # Desktop file must match application name in lowercase with dashes instead of white space. self.setDesktopFileName(f"{title.lower().replace(' ', '-')}.desktop") self.setOrganizationDomain( "https://codesardine.github.io/Jade-Application-Kit") self.setApplicationVersion(__version__)