Esempio n. 1
0
def run(args):
    """Main entrypoint function

    Args:
        args (list): command line arguments to be passed to the application

    Returns:
        int: return code to report back to the shell with
    """
    configure_logging()

    # HACK: this next line was needed to silence an odd warning message generated by Qt
    QApplication.setAttribute(Qt.AA_ShareOpenGLContexts)

    # Configure our application
    app = QApplication(args)
    app.setOrganizationName("The Friendly Coder")
    app.setOrganizationDomain("https://github.com/TheFriendlyCoder")
    app.setApplicationName("FriendlyPics2")
    app.setApplicationVersion(__version__)

    # Configure our main window
    window = MainWindow()
    window.show()

    # Attach the Python logging system to the GUI
    log_handler = GuiLogger(window.findChild(QPlainTextEdit, "debug_log"))
    logging.getLogger().addHandler(log_handler)

    # Run our app
    return app.exec_()
Esempio n. 2
0
def clilaunch(atlas=None, axes=False, output=None):
    app = QApplication(sys.argv)
    app.setApplicationName("Brainrender GUIs")
    ex = App(atlas_name=atlas, axes=axes, screenshots_folder=output)
    app.aboutToQuit.connect(ex.onClose)
    ex.show()
    sys.exit(app.exec_())
Esempio n. 3
0
def qapplication():
    """Either return a reference to an existing application instance
    or create a new one
    :return: A reference to the QApplication object
    """
    app = QApplication.instance()
    if app is None:
        QCoreApplication.setAttribute(Qt.AA_ShareOpenGLContexts)
        argv = sys.argv[:]
        argv[0] = APPNAME  # replace application name
        # Workaround a segfault with the IPython console when using Python 3.5 + PyQt 5
        # Without this using this fix the above combination causes a segfault when the IPython
        # console is started
        # The workaround mentioned in https://groups.google.com/forum/#!topic/leo-editor/ghiIN7irzY0
        # is to ensure readline is imported before the QApplication object is created
        if sys.version_info[0] == 3 and sys.version_info[1] == 5:
            importlib.import_module("readline")
        app = QApplication(argv)
        app.setOrganizationName(ORGANIZATION)
        app.setOrganizationDomain(ORG_DOMAIN)
        app.setApplicationName(APPNAME)
        app.setApplicationVersion(mantid_version_str())
        # Spin up the usage service and set the name for the usage reporting
        # The report is sent when the FrameworkManager kicks up
        UsageService.setApplicationName(APPNAME)

    return app
Esempio n. 4
0
def main(argv: Sequence[str] = None) -> int:
    argv = argv if argv is not None else sys.argv

    command_line_args = parse_commandline(argv)
    exit_code_str = command_line_args.exit_code
    exit_code = int(exit_code_str)
    if mantid.config['usagereports.enabled'] != '1':
        return exit_code

    # On Windows/macOS the plugin locations need to be known before starting
    # QApplication
    if command_line_args.qtdir is not None:
        QCoreApplication.addLibraryPath(command_line_args.qtdir)

    # Qt resources must be imported before QApplication starts
    importlib.import_module(f'mantidqt.dialogs.errorreports.resources_qt{QT_VERSION[0]}')

    if sys.platform == 'darwin':
        qtutils.force_layer_backing_BigSur()

    from qtpy.QtWidgets import QApplication
    app = QApplication(argv)
    # The strings APPNAME, ORG_DOMAIN, ORGANIZATION are duplicated from workbench.config
    app.setOrganizationName(command_line_args.org_name)
    app.setOrganizationDomain(command_line_args.org_domain)
    app.setApplicationName(command_line_args.application)
    QSettings.setDefaultFormat(QSettings.IniFormat)
    form = CrashReportPage(show_continue_terminate=False)
    presenter = ErrorReporterPresenter(form, exit_code_str, command_line_args.application)
    presenter.show_view()
    app.exec_()

    return exit_code
Esempio n. 5
0
def _run():
    app_name = "MNELAB"
    if sys.platform.startswith("darwin"):
        try:  # set bundle name on macOS (app name shown in the menu bar)
            from Foundation import NSBundle
            bundle = NSBundle.mainBundle()
            if bundle:
                info = (bundle.localizedInfoDictionary()
                        or bundle.infoDictionary())
                if info:
                    info["CFBundleName"] = app_name
        except ImportError:
            pass
    matplotlib.use("Qt5Agg")
    app = QApplication(sys.argv)
    app.setApplicationName(app_name)
    app.setOrganizationName("cbrnr")
    if sys.platform.startswith("darwin"):
        app.setAttribute(Qt.AA_DontShowIconsInMenus, True)
    app.setAttribute(Qt.AA_UseHighDpiPixmaps)
    model = Model()
    model.view = MainWindow(model)
    if len(sys.argv) > 1:  # open files from command line arguments
        for f in sys.argv[1:]:
            model.load(f)
    model.view.show()
    sys.exit(app.exec_())
Esempio n. 6
0
def qapplication():
    """Either return a reference to an existing application instance
    or create a new one
    :return: A reference to the QApplication object
    """
    app = QApplication.instance()
    if app is None:
        # attributes that must be set before creating QApplication
        QCoreApplication.setAttribute(Qt.AA_ShareOpenGLContexts)

        argv = sys.argv[:]
        argv[0] = APPNAME  # replace application name
        # Workaround a segfault importing readline with PyQt5
        # This is because PyQt5 messes up pystate (internal) modules_by_index
        # so PyState_FindModule will return null instead of the module address.
        # Readline (so far) is the only module that falls over during init as it blindly uses FindModules result
        # The workaround mentioned in https://groups.google.com/forum/#!topic/leo-editor/ghiIN7irzY0
        if sys.platform == "linux" or sys.platform == "linux2" or sys.platform == "darwin":
            importlib.import_module("readline")

        app = QApplication(argv)
        app.setOrganizationName(ORGANIZATION)
        app.setOrganizationDomain(ORG_DOMAIN)
        app.setApplicationName(APPNAME)
        app.setApplicationVersion(mantid_version_str())
        # Spin up the usage service and set the name for the usage reporting
        # The report is sent when the FrameworkManager kicks up
        UsageService.setApplicationName(APPNAME)

        app.setAttribute(Qt.AA_UseHighDpiPixmaps)
        if hasattr(Qt, 'AA_DisableWindowContextHelpButton'):
            app.setAttribute(Qt.AA_DisableWindowContextHelpButton)

    return app
Esempio n. 7
0
def qapplication():
    """Either return a reference to an existing application instance
    or create a new one
    :return: A reference to the QApplication object
    """
    app = QApplication.instance()
    if app is None:
        QCoreApplication.setAttribute(Qt.AA_ShareOpenGLContexts)
        argv = sys.argv[:]
        argv[0] = APPNAME  # replace application name
        # Workaround a segfault with the IPython console when using Python 3.5 + PyQt 5
        # Without this using this fix the above combination causes a segfault when the IPython
        # console is started
        # The workaround mentioned in https://groups.google.com/forum/#!topic/leo-editor/ghiIN7irzY0
        # is to ensure readline is imported before the QApplication object is created
        if sys.version_info[0] == 3 and sys.version_info[1] == 5:
            importlib.import_module("readline")
        app = QApplication(argv)
        app.setOrganizationName(ORGANIZATION)
        app.setOrganizationDomain(ORG_DOMAIN)
        app.setApplicationName(APPNAME)
        app.setApplicationVersion(mantid_version_str())
        # Spin up the usage service and set the name for the usage reporting
        # The report is sent when the FrameworkManager kicks up
        UsageService.setApplicationName(APPNAME)

        if is_required_version(required_version='5.10.0', version=qVersion()):
            app.setAttribute(Qt.AA_DisableWindowContextHelpButton)

    return app
Esempio n. 8
0
def gui_qt(*, startup_logo=False):
    """Start a Qt event loop in which to run the application.

    Parameters
    ----------
    startup_logo : bool
        Show a splash screen with the napari logo during startup.

    Notes
    -----
    This context manager is not needed if running napari within an interactive
    IPython session. In this case, use the ``%gui qt`` magic command, or start
    IPython with the Qt GUI event loop enabled by default by using
    ``ipython --gui=qt``.
    """
    splash_widget = None
    app = QApplication.instance()
    if not app:
        # if this is the first time the Qt app is being instantiated, we set
        # the name, so that we know whether to raise_ in Window.show()
        app = QApplication(sys.argv)
        app.setApplicationName('napari')
        if startup_logo:
            logopath = join(dirname(__file__), '..', 'resources', 'logo.png')
            splash_widget = QSplashScreen(QPixmap(logopath).scaled(400, 400))
            splash_widget.show()
    yield app
    # if the application already existed before this function was called,
    # there's no need to start it again.  By avoiding unnecessary calls to
    # ``app.exec_``, we avoid blocking.
    if app.applicationName() == 'napari':
        if splash_widget and startup_logo:
            splash_widget.close()
        app.exec_()
Esempio n. 9
0
def get_app_and_window(app_name):
    qt_app = QApplication.instance()
    if qt_app is None:
        qt_app = QApplication(sys.argv)
        qt_app.setOrganizationName("LArray")
        qt_app.setApplicationName(app_name)
        parent = None
    else:
        parent = qt_app.activeWindow()
    return qt_app, parent
Esempio n. 10
0
def main():
    app = QApplication(sys.argv)
    QApplication.setOrganizationName("pyCart3d")
    QApplication.setOrganizationDomain(pyNastran.__website__)
    QApplication.setApplicationName("pyCart3d")
    QApplication.setApplicationVersion(pyNastran.__version__)

    inputs = get_inputs()
    window = MainWindow(inputs)
    sys.exit(app.exec_())
Esempio n. 11
0
def get_qapp():
    """ Return a QApplication instance, creating one if needed. """
    from qtpy.QtWidgets import QApplication
    qapp = QApplication.instance()
    if qapp:
        return qapp
    qapp = QApplication(sys.argv)
    qapp.setApplicationName('MoView')
    qapp.setApplicationDisplayName('MoView')
    qapp.setApplicationVersion(__version__)
    return qapp
Esempio n. 12
0
def run():
    app = QApplication([])
    app.setApplicationName("Broadside")

    log.info("QApp started")

    viewer = Viewer(theme="light",
                    path=Path("/home/sebastian/limbo/projects/test_project"))
    viewer.show()

    sys.exit(app.exec_())
Esempio n. 13
0
    def start(live=False):
        os.environ['QML_DISABLE_DISTANCEFIELD'] = '1'

        app = QApplication(sys.argv)
        app.setApplicationName("APE Main GUI")
        app.setOrganizationName("UES")
        app.setOrganizationDomain("www.ues.com")

        gui = MainGui(live=live)
        signal.signal(signal.SIGINT, lambda *args: gui.shutdown())

        sys.exit(app.exec_())
Esempio n. 14
0
def main(main_file, arguments):
    signal.signal(signal.SIGINT, lambda *args: LiveCodingGui.shutdown())

    app = QApplication(sys.argv)
    app.setOrganizationName('machinekoder.com')
    app.setOrganizationDomain('machinekoder.com')
    app.setApplicationName('Python Qt Live Coding')
    app.setWindowIcon(QIcon(os.path.join(MODULE_PATH, 'icon.png')))

    _gui = LiveCodingGui(arguments, main_file)  # noqa: F841

    sys.exit(app.exec_())
Esempio n. 15
0
def main():
    if len(sys.argv) > 1 and sys.argv[1] == "_test":
        _test_imports()
        return
    parser = CustomParser("PartSeg")
    parser.add_argument(
        "--multiprocessing-fork", dest="mf", action="store_true", help=argparse.SUPPRESS
    )  # Windows bug fix
    sp = parser.add_subparsers()
    sp_a = sp.add_parser("roi_analysis", help="Starts GUI for segmentation analysis")
    sp_s = sp.add_parser("mask_segmentation", help="Starts GUI for segmentation")
    parser.set_defaults(gui="launcher")
    sp_a.set_defaults(gui="roi_analysis")
    sp_s.set_defaults(gui="roi_mask")
    sp_a.add_argument("image", nargs="?", help="image to read on begin", default="")
    sp_a.add_argument("mask", nargs="?", help="mask to read on begin", default=None)
    sp_a.add_argument("--batch", action="store_true", help=argparse.SUPPRESS)
    sp_s.add_argument("image", nargs="?", help="image to read on begin", default="")
    argv = [x for x in sys.argv[1:] if not (x.startswith("parent") or x.startswith("pipe"))]
    args = parser.parse_args(argv)
    # print(args)

    logging.basicConfig(level=logging.INFO)
    if platform.system() == "Darwin":
        multiprocessing.set_start_method("spawn")

    QApplication.setAttribute(Qt.AA_EnableHighDpiScaling)
    my_app = QApplication(sys.argv)
    my_app.setApplicationName("PartSeg")
    my_app.setWindowIcon(QIcon(os.path.join(icons_dir, "icon.png")))

    napari_get_settings(os.path.join(os.path.dirname(state_store.save_folder), "napari"))
    with suppress(ImportError):
        from napari.qt import get_app

        get_app()

    wind = select_window(args)

    try:
        from napari._qt.qthreading import wait_for_workers_to_quit
    except ImportError:
        from napari._qt.threading import wait_for_workers_to_quit
    my_app.aboutToQuit.connect(wait_for_workers_to_quit)
    check_version = CheckVersionThread()
    check_version.start()
    wind.show()
    rc = my_app.exec_()
    del wind  # skipcq: PTC-W0043`
    del my_app  # skipcq: PTC-W0043`
    sys.exit(rc)
Esempio n. 16
0
def main():
    if sys.platform == 'win32':
        import ctypes
        myappid = 'pynastran.pynastrangui.%s' % (pyNastran.__version__
                                                 )  # arbitrary string
        ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID(myappid)

    app = QApplication(sys.argv)
    QApplication.setOrganizationName('pyNastran')
    QApplication.setOrganizationDomain(pyNastran.__website__)
    QApplication.setApplicationName('pyNastran')
    QApplication.setApplicationVersion(pyNastran.__version__)

    w = MainWindow2()
    app.exec_()
def qapplication(test_time=10):
    """Create QApplication instance."""
    app = QApplication.instance()

    if app is None:
        app = QApplication(['Anaconda-Navigator'])
        app.setApplicationName('Anaconda-Navigator')

    test_ci = os.environ.get('TEST_CI')

    if test_ci is not None:
        timer_shutdown = QTimer(app)
        timer_shutdown.timeout.connect(app.quit)
        timer_shutdown.start(test_time * 1000)
    return app
Esempio n. 18
0
def run(argv):
    """Start a QApplication and show the main window

    Parameters
    ----------
    argv : dict
        command line arguments (like ``sys.argv``)

    Returns
    -------
    int
        exit status of the application
    """
    app = QApplication(argv)
    app.setApplicationName("locator")

    ap = argparse.ArgumentParser(
        prog="python -m sdt.gui.locator",
        description=_tr("Locate fluorescent features in images"))
    ap.add_argument("files",
                    metavar="FILE",
                    nargs="*",
                    help=_tr("File to open, optional"))
    ap.add_argument("-p",
                    "--preview",
                    type=lambda x: x in ("t", "1", "true", "yes"),
                    help=_tr("Show preview (true/false), optional"))
    # don't use app.arguments()[1:] since that doesn't work on at least one
    # Windows machine when called as python -m <module name>
    # In that case, "-m" and "<module name>" also end up in the arg list
    args = ap.parse_args(argv[1:])  # first arg is the executable

    try:
        w = MainWindow()
    except Exception as e:
        QMessageBox.critical(None, app.translate("main", "Startup error"),
                             str(e) + "\n\n" + traceback.format_exc())
        return 1

    w.show()

    for f in args.files:
        w.open(f)

    if args.preview is not None:
        w.showPreview = args.preview

    return app.exec_()
Esempio n. 19
0
def qapplication(translate=True, test_time=3):
    """Return QApplication instance
    Creates it if it doesn't already exist"""
    app = QApplication.instance()
    if app is None:
        app = QApplication(['Conda-Manager'])
        app.setApplicationName('Conda-Manager')
    if translate:
        install_translator(app)

    test_travis = os.environ.get('TEST_CI', None)
    if test_travis is not None:
        timer_shutdown = QTimer(app)
        timer_shutdown.timeout.connect(app.quit)
        timer_shutdown.start(test_time*1000)
    return app
Esempio n. 20
0
def launch(*args, atlas_name=None, output=None, screenshots_folder=None):
    """
        Launches the application
    """
    if output is None:
        screenshot_kwargs = output
    else:
        screenshot_kwargs = screenshots_folder

    app = QApplication(sys.argv)
    app.setApplicationName("Brainrender GUIs")
    ex = App(
        *args, atlas_name=atlas_name, screenshots_folder=screenshots_folder
    )
    app.aboutToQuit.connect(ex.onClose)
    ex.show()
    sys.exit(app.exec_())
Esempio n. 21
0
def qapplication():
    """Either return a reference to an existing application instance
    or create a new one
    :return: A reference to the QApplication object
    """
    app = QApplication.instance()
    if app is None:
        QCoreApplication.setAttribute(Qt.AA_ShareOpenGLContexts)
        argv = sys.argv[:]
        argv[0] = APPNAME  # replace application name
        app = QApplication(argv)
        app.setOrganizationName(ORGANIZATION)
        app.setOrganizationDomain(ORG_DOMAIN)
        app.setApplicationName(APPNAME)
        # not calling app.setApplicationVersion(mantid.kernel.version_str())
        # because it needs to happen after logging is monkey-patched in
    return app
Esempio n. 22
0
def cmd_line():
    """the setup.py entry point for ``pyNastranGUI``"""
    # this fixes the icon shown in the windows taskbar to be the custom one (not the python one)
    if sys.platform == 'win32':
        myappid = 'pynastran.pynastrangui.%s' % (gui_utils.__version__
                                                 )  # arbitrary string
        ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID(myappid)

    from qtpy.QtWidgets import QApplication
    app = QApplication(sys.argv)

    QApplication.setOrganizationName("gui_utils")
    QApplication.setOrganizationDomain(gui_utils.__website__)
    QApplication.setApplicationName("gui_utils")
    QApplication.setApplicationVersion(gui_utils.__version__)
    inputs = get_inputs()
    #inputs['app'] = app
    MainWindow(inputs)
    app.exec_()
Esempio n. 23
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("-d", "--dev", type=bool, default=False, required=False,
                        help="Enable Developement mode")
    LOG_FILENAME = 'log.out'
    parser.add_argument("-lp", "--logpath", type=str, default=LOG_FILENAME,
                        required=False, help="Path to save log file")
    parser.add_argument("--headless", type=bool, default=False,
                        required=False, help="Whether to run software headless")
    parser.add_argument("-p", "--parameter", type=str, default=False,
                        required=False, help="Path to parameter file")
    parser.add_argument("-ll", "--loglevel", type=str, default="error",
                        required=False,
                        choices=['debug', 'info', 'warning', 'error', 'critical'])
    args = parser.parse_args()
    LEVELS = {'debug': logging.DEBUG,
              'info': logging.INFO,
              'warning': logging.WARNING,
              'error': logging.ERROR,
             'critical': logging.CRITICAL}

    level = LEVELS.get(args.loglevel, logging.NOTSET)
    logging.basicConfig(filename=args.logpath, level=level)
    logger = logging.getLogger("CIDAN")
    logger.debug("Program started")
    if args.headless:
        data_handler = DataHandler.DataHandler("",
                                               "",
                                               trials=[],
                                               save_dir_already_created=True,
                                               parameter_file=args.parameter,
                                               load_into_mem=True)
        data_handler.calculate_filters()
        data_handler.calculate_roi_extraction()
        data_handler.export()
    else:
        app = QApplication([])
        app.setApplicationName("CIDAN")
        widget = MainWindow.MainWindow(dev=args.dev)

        sys.exit(app.exec_())
Esempio n. 24
0
class ApplicationBackend(BaseApplicationBackend):
    _app: QApplication

    def _mgui_get_backend_name(self):
        return "qt"

    def _mgui_process_events(self):
        app = self._mgui_get_native_app()
        app.flush()
        app.processEvents()

    def _mgui_run(self):
        app = self._mgui_get_native_app()
        # only start the event loop if magicgui created it
        if app.applicationName() == APPLICATION_NAME:
            return app.exec_()

    def _mgui_quit(self):
        return self._mgui_get_native_app().quit()

    def _mgui_get_native_app(self):
        # Get native app
        self._app = QApplication.instance()
        if not self._app:
            QApplication.setAttribute(Qt.AA_EnableHighDpiScaling)
            self._app = QApplication(sys.argv)
            self._app.setApplicationName(APPLICATION_NAME)
        return self._app

    def _mgui_start_timer(self, interval=0, on_timeout=None, single=False):
        self._timer = QTimer()
        if on_timeout:
            self._timer.timeout.connect(on_timeout)
        self._timer.setSingleShot(single)
        self._timer.setInterval(interval)
        self._timer.start()

    def _mgui_stop_timer(self):
        if getattr(self, "_timer", None):
            self._timer.stop()
Esempio n. 25
0
def main():
    """ Main operating script

    main() is the main function that is calling the other procedures and
    functions. First, it will call the LaunchWindow() class and display and
    wait for the proper user inputs. Next, it will open the main UI window.
    In this window, all of the image processing tasks can be completed if
    necesssary.

    Args:
        None

    Returns:
        None

        """
    if not QApplication.instance():
        app = QApplication(sys.argv)
    else:
        app = QApplication.instance()

    # Display the config.py file
    app.setWindowIcon(QtGui.QIcon(config.ICON))
    app.setApplicationName(config.TITLE)

    # Call the launch windows
    window = LaunchDialog()

    # Obtain data from launch window
    user, batch, img_group, location = get_launch_data(window)

    if user and batch and img_group and location:
        frame = MainWindow(user, batch, img_group, location)
        frame.setWindowTitle(config.TITLE)
        frame.show()
        app.exec_()
    else:
        app.quit()
Esempio n. 26
0
        settings.beginGroup('MainWindow')
        self.resize(settings.value('size', QSize(400, 400)))
        self.move(settings.value('pos', QPoint(200, 200)))
        self.container.readSettings(settings)
        settings.endGroup()

    def writeSettings(self, settings):
        """ Save the applications's settings persistently. """
        settings.beginGroup('MainWindow')
        settings.setValue('size', self.size())
        settings.setValue('pos', self.pos())
        self.container.writeSettings(settings)
        settings.endGroup()


if __name__ == '__main__':
    # Set up some application basics for saving settings
    QApplication.setOrganizationName('BNL')
    QApplication.setOrganizationDomain('bnl.gov')
    QApplication.setApplicationName('QCamera')

    # Create the Qt Application
    app = QApplication(sys.argv)

    # Create and show the form
    form = Form()
    form.show()

    # Run the main Qt loop
    sys.exit(app.exec_())
Esempio n. 27
0

# Set Qt input method variable to use fcitx / ibus if config.fcitx / config.ibus is "True"
if config.fcitx:
    os.environ["QT_IM_MODULE"] = "fcitx"
elif config.ibus:
    os.environ["QT_IM_MODULE"] = "ibus"

# Set Qt input method variable to use Qt virtual keyboards if config.virtualKeyboard is "True"
if config.virtualKeyboard:
    os.environ["QT_IM_MODULE"] = "qtvirtualkeyboard"

# Start PySide2 gui
app = QApplication(sys.argv)
# Set application name
app.setApplicationName("UniqueBible.app")
app.setApplicationDisplayName("UniqueBible.app")
# When application name is changed
app.applicationNameChanged.connect(nameChanged)
# Assign a function to save configurations when the app is closed.
app.aboutToQuit.connect(exitApplication)
# Apply window style
if config.windowStyle and config.windowStyle in QStyleFactory.keys():
    app.setStyle(config.windowStyle)
# Apply theme style
if config.qtMaterial and config.qtMaterialTheme:
    apply_stylesheet(app, theme=config.qtMaterialTheme)
    config.theme = "dark" if config.qtMaterialTheme.startswith("dark_") else "default"
else:
    app.setPalette(Themes.getPalette())
# Active verse number colour
Esempio n. 28
0
        for p in POINTS_2:
            lons_2.append(p[1])
            lats_2.append(p[0])
        linesGroupItem = view.scene().addLinesGroup(lons_2, lats_2)
        linesGroupItem.setLineStyle(POINTS_2_COLORS, width=POINTS_2_SIZES)

        legendItem = view.scene().addLegend()
        legendItem.addPoint('Point 1', '#FF0000', border=None)
        legendItem.addRect('Rect 2', '#00FF00', border=None)
        legendItem.addPoint('Circle 3', '#0000FF', border=None)
        legendItem.addRect('Sphere 4', '#00FFFF', border=None)
        legendItem.addPoint('Polygon 5', '#FF00FF', border=None)

        scaleItem = view.scene().addScale(anchor=Qt.BottomRightCorner)


def main():
    w = MapZoom()
    w.setWindowTitle("OpenStreetMap")

    w.resize(800, 600)
    w.show()

    return app.exec_()

if __name__ == '__main__':
    app = QApplication([])
    app.setApplicationName("TileMap")

    sys.exit(main())
Esempio n. 29
0
        os.environ["QT_QPA_PLATFORM"] = "offscreen"
    if getattr(sys, 'frozen', False):
        application_path = os.path.dirname(sys.executable)
    elif __file__:
        application_path = os.path.dirname(__file__)
    else:
        application_path = "."
    logging.debug("Application path is {}".format(application_path))
    os.chdir(application_path)
    sys.path.insert(0, os.path.abspath(MODULES_PATH))
    sys.path.append(os.path.abspath(CLIENT_PATH))

    QApplication.setAttribute(Qt.AA_UseHighDpiPixmaps)
    QApplication.setAttribute(Qt.AA_EnableHighDpiScaling)
    QApplication.setQuitOnLastWindowClosed(False)

    app = QApplication(sys.argv)
    app.setApplicationName(__app_name__)
    app.setApplicationVersion(__version__)
    app.setApplicationDisplayName(__app_name__)

    app.setStyleSheet(qrainbowstyle.load_stylesheet(style="Oceanic"))
    font = app.font()
    font.setPointSize(9)
    app.setFont(font)

    m = Main(args)
    m.connect_log_signal(logger.install_signal_handler())

    sys.exit(app.exec_())
Esempio n. 30
0
def cmd_line():
    """the setup.py entry point for ``pyNastranGUI``"""
    # this fixes the icon shown in the windows taskbar to be the custom one (not the python one)
    if sys.platform == 'win32':
        myappid = 'pynastran.pynastrangui.%s' % (pyNastran.__version__
                                                 )  # arbitrary string
        ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID(myappid)

    from qtpy.QtWidgets import QApplication
    app = QApplication(sys.argv)

    if 0:  # pragma: no cover
        try:
            import qtmodern.styles
        except ImportError:
            pass
        else:
            qtmodern.styles.dark(app)

    #app.setStyle('Fusion')
    #app.setStyle('WindowsXP')

    #if 0:
    #import qtpy.QtGui as QtGui
    #import qtpy.QtCore as QtCore
    #palette = QtGui.QPalette()
    #palette.setColor(QtGui.QPalette.Window, QtGui.QColor(53,53,53))
    #palette.setColor(QtGui.QPalette.WindowText, QtCore.Qt.white)
    #palette.setColor(QtGui.QPalette.Base, QtGui.QColor(15,15,15))
    #palette.setColor(QtGui.QPalette.AlternateBase, QtGui.QColor(53,53,53))
    #palette.setColor(QtGui.QPalette.ToolTipBase, QtCore.Qt.white)
    #palette.setColor(QtGui.QPalette.ToolTipText, QtCore.Qt.white)
    #palette.setColor(QtGui.QPalette.Text, QtCore.Qt.white)
    #palette.setColor(QtGui.QPalette.Button, QtGui.QColor(53,53,53))
    #palette.setColor(QtGui.QPalette.ButtonText, QtCore.Qt.white)
    #palette.setColor(QtGui.QPalette.BrightText, QtCore.Qt.red)

    #palette.setColor(QtGui.QPalette.Highlight, QtGui.QColor(142,45,197).lighter())
    #palette.setColor(QtGui.QPalette.HighlightedText, QtCore.Qt.black)
    #app.setPalette(palette)

    #if 1:
    stylesheet = get_stylesheet()
    if stylesheet:
        app.setStyleSheet(stylesheet)

    if 0:  # pragma: no cover
        import qtpy.QtGui as QtGui
        #import qtpy.QtCore as QtCore
        from qtpy.QtGui import QPalette, QColor
        dark_palette = QtGui.QPalette()
        dark_palette.setColor(QPalette.WindowText, QColor(180, 180, 180))
        dark_palette.setColor(QPalette.Button, QColor(53, 53, 53))
        dark_palette.setColor(QPalette.Light, QColor(180, 180, 180))
        dark_palette.setColor(QPalette.Midlight, QColor(90, 90, 90))
        dark_palette.setColor(QPalette.Dark, QColor(35, 35, 35))
        dark_palette.setColor(QPalette.Text, QColor(180, 180, 180))
        dark_palette.setColor(QPalette.BrightText, QColor(180, 180, 180))
        dark_palette.setColor(QPalette.ButtonText, QColor(180, 180, 180))
        dark_palette.setColor(QPalette.Base, QColor(42, 42, 42))
        dark_palette.setColor(QPalette.Window, QColor(53, 53, 53))
        dark_palette.setColor(QPalette.Shadow, QColor(20, 20, 20))
        dark_palette.setColor(QPalette.Highlight, QColor(42, 130, 218))
        dark_palette.setColor(QPalette.HighlightedText, QColor(180, 180, 180))
        dark_palette.setColor(QPalette.Link, QColor(56, 252, 196))
        dark_palette.setColor(QPalette.AlternateBase, QColor(66, 66, 66))
        dark_palette.setColor(QPalette.ToolTipBase, QColor(53, 53, 53))
        dark_palette.setColor(QPalette.ToolTipText, QColor(180, 180, 180))

        # disabled
        dark_palette.setColor(QPalette.Disabled, QPalette.WindowText,
                              QColor(127, 127, 127))
        dark_palette.setColor(QPalette.Disabled, QPalette.Text,
                              QColor(127, 127, 127))
        dark_palette.setColor(QPalette.Disabled, QPalette.ButtonText,
                              QColor(127, 127, 127))
        dark_palette.setColor(QPalette.Disabled, QPalette.Highlight,
                              QColor(80, 80, 80))
        dark_palette.setColor(QPalette.Disabled, QPalette.HighlightedText,
                              QColor(127, 127, 127))
        app.setPalette(dark_palette)

    QApplication.setOrganizationName("pyNastran")
    QApplication.setOrganizationDomain(pyNastran.__website__)
    QApplication.setApplicationName("pyNastran")
    QApplication.setApplicationVersion(pyNastran.__version__)
    inputs = get_inputs(print_inputs=False)
    #inputs['app'] = app
    MainWindow(inputs)
    app.exec_()
Esempio n. 31
0
            plugin_config.reset_to_defaults(section='shortcuts')


try:
    CONF = ConfigurationManager()
except Exception:
    from qtpy.QtWidgets import QApplication, QMessageBox

    # Check if there's an app already running
    app = QApplication.instance()

    # Create app, if there's none, in order to display the message below.
    # NOTE: Don't use the functions we have to create a QApplication here
    # because they could import CONF at some point, which would make this
    # fallback fail.
    # See issue spyder-ide/spyder#17889
    if app is None:
        app = QApplication(['Spyder'])
        app.setApplicationName('Spyder')

    reset_reply = QMessageBox.critical(
        None, 'Spyder',
        _("There was an error while loading Spyder configuration options. "
          "You need to reset them for Spyder to be able to launch.\n\n"
          "Do you want to proceed?"), QMessageBox.Yes, QMessageBox.No)
    if reset_reply == QMessageBox.Yes:
        reset_config_files()
        QMessageBox.information(None, 'Spyder',
                                _("Spyder configuration files resetted!"))
    os._exit(0)
Esempio n. 32
0
def main():
    """Execute QDarkStyle example."""
    parser = argparse.ArgumentParser(
        description=__doc__,
        formatter_class=argparse.RawDescriptionHelpFormatter)
    parser.add_argument(
        '--qt_from',
        default='qtpy',
        type=str,
        choices=[
            'pyqt5', 'pyqt', 'pyside2', 'pyside', 'qtpy', 'pyqtgraph', 'qt.py'
        ],
        help=
        "Choose which binding and/or abstraction is to be used to run the example."
    )
    parser.add_argument(
        '--no_dark',
        action='store_true',
        help="Exihibts the original window (without jam_darkstyle).")
    parser.add_argument('--test',
                        action='store_true',
                        help="Auto close window after 2s.")
    parser.add_argument('--reset',
                        action='store_true',
                        help="Reset GUI settings (position, size) then opens.")
    parser.add_argument('--screenshots',
                        action='store_true',
                        help="Generate screenshots on images folder.")

    # Parsing arguments from command line
    args = parser.parse_args()

    # To avoid problems when testing without screen
    if args.test or args.screenshots:
        os.environ['QT_QPA_PLATFORM'] = 'offscreen'

    # Set QT_API variable before importing QtPy
    if args.qt_from in ['pyqt', 'pyqt5', 'pyside', 'pyside2']:
        os.environ['QT_API'] = args.qt_from
    elif args.qt_from == 'pyqtgraph':
        os.environ['QT_API'] = os.environ['PYQTGRAPH_QT_LIB']
    elif args.qt_from in ['qt.py', 'qt']:
        try:
            import Qt
        except ImportError:
            print('Could not import Qt (Qt.Py)')
        else:
            os.environ['QT_API'] = Qt.__binding__

    # QtPy imports
    from qtpy import API_NAME, QT_VERSION, PYQT_VERSION, PYSIDE_VERSION
    from qtpy import __version__ as QTPY_VERSION
    from qtpy.QtWidgets import (QApplication, QMainWindow, QDockWidget,
                                QStatusBar, QLabel, QPushButton, QMenu)
    from qtpy.QtCore import QTimer, Qt, QSettings

    # Set API_VERSION variable
    API_VERSION = ''

    if PYQT_VERSION:
        API_VERSION = PYQT_VERSION
    elif PYSIDE_VERSION:
        API_VERSION = PYSIDE_VERSION
    else:
        API_VERSION = 'Not found'

    # Import examples UI
    from mw_menus_ui import Ui_MainWindow as ui_main

    from dw_buttons_ui import Ui_DockWidget as ui_buttons
    from dw_displays_ui import Ui_DockWidget as ui_displays
    from dw_inputs_fields_ui import Ui_DockWidget as ui_inputs_fields
    from dw_inputs_no_fields_ui import Ui_DockWidget as ui_inputs_no_fields

    from dw_widgets_ui import Ui_DockWidget as ui_widgets
    from dw_views_ui import Ui_DockWidget as ui_views
    from dw_containers_tabs_ui import Ui_DockWidget as ui_containers_tabs
    from dw_containers_no_tabs_ui import Ui_DockWidget as ui_containers_no_tabs

    # create the application
    app = QApplication(sys.argv)
    app.setOrganizationName('QDarkStyle')
    app.setApplicationName('QDarkStyle Example')

    style = ''

    if not args.no_dark:
        style = jam_darkstyle.load_stylesheet()

    app.setStyleSheet(style)

    # create main window
    window = QMainWindow()
    window.setObjectName('mainwindow')

    ui = ui_main()
    ui.setupUi(window)

    title = ("QDarkStyle Example - " + "(QDarkStyle=v" +
             jam_darkstyle.__version__ + ", QtPy=v" + QTPY_VERSION + ", " +
             API_NAME + "=v" + API_VERSION + ", Qt=v" + QT_VERSION +
             ", Python=v" + platform.python_version() + ")")

    _logger.info(title)

    window.setWindowTitle(title)

    # Create docks for buttons
    dw_buttons = QDockWidget()
    dw_buttons.setObjectName('buttons')
    ui_buttons = ui_buttons()
    ui_buttons.setupUi(dw_buttons)
    window.addDockWidget(Qt.RightDockWidgetArea, dw_buttons)

    # Add actions on popup toolbuttons
    menu = QMenu()

    for action in ['Action A', 'Action B', 'Action C']:
        menu.addAction(action)

    ui_buttons.toolButtonDelayedPopup.setMenu(menu)
    ui_buttons.toolButtonInstantPopup.setMenu(menu)
    ui_buttons.toolButtonMenuButtonPopup.setMenu(menu)

    # Create docks for buttons
    dw_displays = QDockWidget()
    dw_displays.setObjectName('displays')
    ui_displays = ui_displays()
    ui_displays.setupUi(dw_displays)
    window.addDockWidget(Qt.RightDockWidgetArea, dw_displays)

    # Create docks for inputs - no fields
    dw_inputs_no_fields = QDockWidget()
    dw_inputs_no_fields.setObjectName('inputs_no_fields')
    ui_inputs_no_fields = ui_inputs_no_fields()
    ui_inputs_no_fields.setupUi(dw_inputs_no_fields)
    window.addDockWidget(Qt.RightDockWidgetArea, dw_inputs_no_fields)

    # Create docks for inputs - fields
    dw_inputs_fields = QDockWidget()
    dw_inputs_fields.setObjectName('inputs_fields')
    ui_inputs_fields = ui_inputs_fields()
    ui_inputs_fields.setupUi(dw_inputs_fields)
    window.addDockWidget(Qt.RightDockWidgetArea, dw_inputs_fields)

    # Create docks for widgets
    dw_widgets = QDockWidget()
    dw_widgets.setObjectName('widgets')
    ui_widgets = ui_widgets()
    ui_widgets.setupUi(dw_widgets)
    window.addDockWidget(Qt.LeftDockWidgetArea, dw_widgets)

    # Create docks for views
    dw_views = QDockWidget()
    dw_views.setObjectName('views')
    ui_views = ui_views()
    ui_views.setupUi(dw_views)
    window.addDockWidget(Qt.LeftDockWidgetArea, dw_views)

    # Create docks for containers - no tabs
    dw_containers_no_tabs = QDockWidget()
    dw_containers_no_tabs.setObjectName('containers_no_tabs')
    ui_containers_no_tabs = ui_containers_no_tabs()
    ui_containers_no_tabs.setupUi(dw_containers_no_tabs)
    window.addDockWidget(Qt.LeftDockWidgetArea, dw_containers_no_tabs)

    # Create docks for containters - tabs
    dw_containers_tabs = QDockWidget()
    dw_containers_tabs.setObjectName('containers_tabs')
    ui_containers_tabs = ui_containers_tabs()
    ui_containers_tabs.setupUi(dw_containers_tabs)
    window.addDockWidget(Qt.LeftDockWidgetArea, dw_containers_tabs)

    # Tabify right docks
    window.tabifyDockWidget(dw_buttons, dw_displays)
    window.tabifyDockWidget(dw_displays, dw_inputs_fields)
    window.tabifyDockWidget(dw_inputs_fields, dw_inputs_no_fields)

    # Tabify left docks
    window.tabifyDockWidget(dw_containers_no_tabs, dw_containers_tabs)
    window.tabifyDockWidget(dw_containers_tabs, dw_widgets)
    window.tabifyDockWidget(dw_widgets, dw_views)

    # Issues #9120, #9121 on Spyder
    qstatusbar = QStatusBar()
    qstatusbar.addWidget(
        QLabel('Issue Spyder #9120, #9121 - background not matching.'))
    qstatusbar.addWidget(QPushButton('OK'))

    # Add info also in status bar for screenshots get it
    qstatusbar.addWidget(QLabel('INFO: ' + title))
    window.setStatusBar(qstatusbar)

    # Todo: add report info and other info in HELP graphical

    # Auto quit after 2s when in test mode
    if args.test:
        QTimer.singleShot(2000, app.exit)

    # Save screenshots for different displays and quit
    if args.screenshots:
        window.showFullScreen()
        create_screenshots(app, window, args.no_dark)
    # Do not read settings when taking screenshots - like reset
    else:
        _read_settings(window, args.reset, QSettings)
        window.showMaximized()

    app.exec_()
    _write_settings(window, QSettings)

    return window