コード例 #1
0
ファイル: iconfont.py プロジェクト: slaclab/pydm
    def load_font(self, ttf_filename, charmap_filename):

        def hook(obj):
            result = {}
            for key in obj:
                result[key] = unichr(int(obj[key], 16))
            return result

        if self.char_map is None:
            cache_key = ttf_filename + "|" + charmap_filename
            ttf_fname = os.path.join(os.path.dirname(os.path.realpath(__file__)), ttf_filename)
            font_id = QFontDatabase.addApplicationFont(ttf_fname)
            if font_id >= 0:
                font_families = QFontDatabase.applicationFontFamilies(font_id)
            else:
                cache = self.loaded_fonts.get(cache_key, None)
                if cache is None:
                    raise OSError("Could not load ttf file for icon font.")
                else:
                    self.char_map = cache['char_map']
                    self.font_name = cache['font_name']
                    return

            self.font_name = font_families[0]

            with open(os.path.join(os.path.dirname(os.path.realpath(__file__)), charmap_filename), 'r') as codes:
                self.char_map = json.load(codes, object_hook=hook)

            self.loaded_fonts[cache_key] = {'char_map': self.char_map, 'font_name': self.font_name}
コード例 #2
0
    def load_font(self, ttf_filename, charmap_filename):
        def hook(obj):
            result = {}
            for key in obj:
                result[key] = unichr(int(obj[key], 16))
            return result

        if self.char_map is None:
            cache_key = ttf_filename + "|" + charmap_filename
            ttf_fname = os.path.join(
                os.path.dirname(os.path.realpath(__file__)), ttf_filename)
            font_id = QFontDatabase.addApplicationFont(ttf_fname)
            if font_id >= 0:
                font_families = QFontDatabase.applicationFontFamilies(font_id)
            else:
                cache = self.loaded_fonts.get(cache_key, None)
                if cache is None:
                    raise OSError("Could not load ttf file for icon font.")
                else:
                    self.char_map = cache['char_map']
                    self.font_name = cache['font_name']
                    return

            self.font_name = font_families[0]

            with open(
                    os.path.join(os.path.dirname(os.path.realpath(__file__)),
                                 charmap_filename), 'r') as codes:
                self.char_map = json.load(codes, object_hook=hook)

            self.loaded_fonts[cache_key] = {
                'char_map': self.char_map,
                'font_name': self.font_name
            }
コード例 #3
0
ファイル: launcher.py プロジェクト: raman325/guiscrcpy
def bootstrap(cfgmgr,
              theme='Breeze',
              aot=True,
              debug__no_scrcpy=False,
              hide_wm_frame=True):
    """
    Launch the guiscrcpy window
    :return:
    """
    config = cfgmgr.get_config()
    # enable High DPI scaling
    QApplication.setAttribute(QtCore.Qt.AA_EnableHighDpiScaling, True)
    # use HIGH DPI icons
    QApplication.setAttribute(QtCore.Qt.AA_UseHighDpiPixmaps, True)
    # init core
    app = QtWidgets.QApplication([])

    # load fonts
    font_database = QFontDatabase()
    for font in FONTS:
        s = font_database.addApplicationFont(
            ':/font/fonts/{ttf}'.format(ttf=font))
        if s == -1:  # loading the font failed
            # https://doc.qt.io/qt-5/qfontdatabase.html
            print(fc("{y}Failed to load {ttf} font.{rst}", ttf=font))

    # set theme
    app.setStyle(theme)
    # apply stylesheet
    if theme == 'Breeze':
        # The Qdarkstylesheet is based on Breeze, lets load them on default
        app.setStyleSheet(dark_stylesheet())

    # load splash
    splash_pix = QPixmap(":/res/ui/guiscrcpy-branding.png")
    splash = QtWidgets.QSplashScreen(splash_pix)
    splash.setMask(splash_pix.mask())
    splash.show()
    app.processEvents()

    # on windows, users are likely not to add the scrcpy-server to the
    # SCRCPY_SERVER_PATH
    cfgmgr.update_config(set_scrcpy_server_path(config))
    cfgmgr.write_file()
    adb = AndroidDebugBridge(cfgmgr.get_config().get('adb'))
    scrcpy = ScrcpyBridge(cfgmgr.get_config().get('scrcpy'))
    cfgmgr['adb'] = adb.get_path()
    cfgmgr['scrcpy'] = scrcpy.get_path()
    guiscrcpy = InterfaceGuiscrcpy(cfgmgr=cfgmgr,
                                   adb=adb,
                                   scrcpy=scrcpy,
                                   force_window_frame=not hide_wm_frame,
                                   panels_not_always_on_top=not aot,
                                   debug__no_scrcpy=debug__no_scrcpy)
    guiscrcpy.show()
    app.processEvents()
    splash.hide()
    app.exec_()
コード例 #4
0
def bootstrap(
    app: QtWidgets.QApplication,
    config_manager: InterfaceConfig,
    theme: str = "Breeze",
    aot: bool = True,
    debug_no_scrcpy: bool = False,
    hide_wm_frame: bool = True,
):
    """
    Launch the guiscrcpy window
    :return:
    """
    config = config_manager.get_config()

    # load fonts
    font_database = QFontDatabase()
    for font in FONTS:
        s = font_database.addApplicationFont(
            ":/font/fonts/{ttf}".format(ttf=font))
        if s == -1:  # loading the font failed
            # https://doc.qt.io/qt-5/qfontdatabase.html
            print(fc("{y}Failed to load {ttf} font.{rst}", ttf=font))

    # set theme
    app.setStyle(theme)
    # apply stylesheet
    if theme == "Breeze":
        # The Qdarkstylesheet is based on Breeze, lets load them on default
        app.setStyleSheet(dark_stylesheet())

    # load splash
    splash_pix = QPixmap(":/res/ui/guiscrcpy-branding.png")
    splash = QtWidgets.QSplashScreen(splash_pix)
    splash.setMask(splash_pix.mask())
    splash.show()
    app.processEvents()

    # on windows, users are likely not to add the scrcpy-server to the
    # SCRCPY_SERVER_PATH
    config_manager.update_config(set_scrcpy_server_path(config))
    config_manager.write_file()
    adb = AndroidDebugBridge(config_manager.get_config().get("adb"))
    scrcpy = ScrcpyBridge(config_manager.get_config().get("scrcpy"))
    config_manager["adb"] = adb.get_path()
    config_manager["scrcpy"] = scrcpy.get_path()
    guiscrcpy = InterfaceGuiscrcpy(
        config_manager=config_manager,
        adb=adb,
        scrcpy=scrcpy,
        force_window_frame=not hide_wm_frame,
        panels_not_always_on_top=not aot,
        debug_no_scrcpy=debug_no_scrcpy,
    )
    guiscrcpy.show()
    app.processEvents()
    splash.hide()
    app.exec_()
コード例 #5
0
ファイル: window.py プロジェクト: keshabb/vidify
    def __init__(self, config: Config) -> None:
        """
        Main window with the GUI and whatever player is being used.
        """

        super().__init__()
        self.setWindowTitle('vidify')

        # Setting the window to stay on top
        if config.stay_on_top:
            self.setWindowFlags(Qt.WindowStaysOnTopHint)

        # Setting the fullscreen and window size
        if config.fullscreen:
            self.showFullScreen()
        else:
            self.resize(config.width or 800, config.height or 600)

        self.layout = QHBoxLayout(self)
        self.layout.setContentsMargins(0, 0, 0, 0)
        self.layout.setSpacing(0)

        # Loading the used fonts (Inter)
        font_db = QFontDatabase()
        for font in Res.fonts:
            font_db.addApplicationFont(font)

        # Initializing the player and saving the config object in the window.
        self.player = initialize_player(config.player, config)
        logging.info("Using %s as the player", config.player)
        self.config = config

        # The audiosync feature is optional until it's more stable.
        if self.config.audiosync:
            from vidify.audiosync import AudiosyncWorker
            self.audiosync = AudiosyncWorker()
        else:
            self.audiosync = None

        # The API initialization is more complex. For more details, please
        # check the flow diagram in vidify.api. First we have to check if
        # the API is saved in the config:
        try:
            api_data = get_api_data(config.api)
        except KeyError:
            # Otherwise, the user is prompted for an API. After choosing one,
            # it will be initialized from outside this function.
            logging.info("API not found: prompting the user")
            self.API_selection = APISelection()
            self.layout.addWidget(self.API_selection)
            self.API_selection.api_chosen.connect(self.on_api_selection)
        else:
            logging.info("Using %s as the API", config.api)
            self.initialize_api(api_data)
コード例 #6
0
ファイル: launcher_main.py プロジェクト: Anodarai/PartSeg
def _test_imports():
    print("start_test_import")
    from qtpy.QtWidgets import QApplication

    app = QApplication([])
    from napari._qt.widgets.qt_console import QtConsole

    from PartSeg import plugins
    from PartSeg._launcher.main_window import MainWindow
    from PartSeg._roi_analysis.main_window import MainWindow as AnalysisMain
    from PartSeg._roi_mask.main_window import MainWindow as MaskMain
    from PartSeg.common_backend.base_argparser import _setup_sentry

    _setup_sentry()
    plugins.register()
    w1 = AnalysisMain("test")
    w2 = MaskMain("test")
    w3 = MainWindow("test")
    console = QtConsole()
    if QFontDatabase.addApplicationFont(os.path.join(font_dir, "Symbola.ttf")) == -1:
        raise ValueError("Error with loading Symbola font")
    del w1
    del w2
    del w3
    del app
    del console
    print("end_test_import")
コード例 #7
0
ファイル: fonts.py プロジェクト: robertapplin/mantid
def text_font():
    """Return the first monospace font for this system.
    The font is cached on first access.
    """
    global _TEXT_FONT_CACHE
    if _TEXT_FONT_CACHE is None:
        fontdb = QFontDatabase()
        families = fontdb.families()
        for family in MONOSPACE:
            if family in families:
                _TEXT_FONT_CACHE = QFont(family)
                break
        _TEXT_FONT_CACHE.setPointSize(PT_SIZE)
        _TEXT_FONT_CACHE.setFixedPitch(True)

    return _TEXT_FONT_CACHE
コード例 #8
0
def load_font(font_name, font_file):
    # NOTE: you need to have created a QApplication() first (see
    # qtw.Widgets.Application) for this to work correctly, or you will get
    # a crash!
    font_id = QFontDatabase.addApplicationFont(font_file)
    if font_id < 0:
        raise ValueError("Unspecified Qt problem loading font from '%s'" %
                         (font_file))

    font_family = QFontDatabase.applicationFontFamilies(font_id)[0]

    if font_name != font_family:
        # If Qt knows this under a different name, add an alias
        font_asst.add_alias(font_name, font_family)

    return font_name
コード例 #9
0
 def loadFont(self, font_path):
     """Loads a font file into the font database. The path can specify the
     location of a font file or a qresource."""
     LOG.debug("Loading custom font: %s" % font_path)
     res = QFontDatabase.addApplicationFont(font_path)
     if res != 0:
         LOG.error("Failed to load font: %s", font_path)
コード例 #10
0
def load_font(font_name, font_file):
    # NOTE: you need to have created a QApplication() first (see
    # qtw.Widgets.Application) for this to work correctly, or you will get
    # a crash!
    font_id = QFontDatabase.addApplicationFont(font_file)
    if font_id < 0:
        raise ValueError("Unspecified Qt problem loading font from '%s'" % (
            font_file))

    font_family = QFontDatabase.applicationFontFamilies(font_id)[0]

    if font_name != font_family:
        # If Qt knows this under a different name, add an alias
        font_asst.add_alias(font_name, font_family)

    return font_name
コード例 #11
0
ファイル: mainwindow.py プロジェクト: robertapplin/mantid
    def readSettings(self, settings):
        qapp = QApplication.instance()

        # get the saved window geometry
        window_size = settings.get('MainWindow/size')
        if not isinstance(window_size, QSize):
            window_size = QSize(*window_size)
        window_pos = settings.get('MainWindow/position')
        if not isinstance(window_pos, QPoint):
            window_pos = QPoint(*window_pos)
        if settings.has('MainWindow/font'):
            font_string = settings.get('MainWindow/font').split(',')
            font = QFontDatabase().font(font_string[0], font_string[-1],
                                        int(font_string[1]))
            qapp.setFont(font)

        # reset font for ipython console to ensure it stays monospace
        self.ipythonconsole.console.reset_font()

        # make sure main window is smaller than the desktop
        desktop = QDesktopWidget()

        # this gives the maximum screen number if the position is off screen
        screen = desktop.screenNumber(window_pos)

        # recalculate the window size
        desktop_geom = desktop.availableGeometry(screen)
        w = min(desktop_geom.size().width(), window_size.width())
        h = min(desktop_geom.size().height(), window_size.height())
        window_size = QSize(w, h)

        # and position it on the supplied desktop screen
        x = max(window_pos.x(), desktop_geom.left())
        y = max(window_pos.y(), desktop_geom.top())
        if x + w > desktop_geom.right():
            x = desktop_geom.right() - w
        if y + h > desktop_geom.bottom():
            y = desktop_geom.bottom() - h
        window_pos = QPoint(x, y)

        # set the geometry
        self.resize(window_size)
        self.move(window_pos)

        # restore window state
        if settings.has('MainWindow/state'):
            if not self.restoreState(settings.get('MainWindow/state'),
                                     SAVE_STATE_VERSION):
                logger.warning(
                    "The previous layout of workbench is not compatible with this version, reverting to default layout."
                )
        else:
            self.setWindowState(Qt.WindowMaximized)

        # read in settings for children
        AlgorithmInputHistory().readSettings(settings)
        for widget in self.widgets:
            if hasattr(widget, 'readSettingsIfNotDone'):
                widget.readSettingsIfNotDone(settings)
コード例 #12
0
ファイル: presenter.py プロジェクト: gemmaguest/mantid
 def action_main_font_button_clicked(self):
     font = None
     if CONF.has(GeneralProperties.FONT.value):
         font_string = CONF.get(GeneralProperties.FONT.value).split(',')
         if len(font_string) > 2:
             font = QFontDatabase().font(font_string[0], font_string[-1], int(font_string[1]))
     font_dialog = self.view.create_font_dialog(self.parent, font)
     font_dialog.fontSelected.connect(self.action_font_selected)
コード例 #13
0
 def addApplicationFont(self, font_path):
     """Loads a font file into the font database. The path can specify the
     location of a font file or a qresource."""
     LOG.debug("Loading custom font: %s" % font_path)
     res = QFontDatabase.addApplicationFont(font_path)
     # per QT docs -1 is error and 0+ is index to font loaded for later use
     if res < 0:
         LOG.error("Failed to load font: %s", font_path)
コード例 #14
0
    def readSettings(self, settings):
        qapp = QApplication.instance()
        qapp.setAttribute(Qt.AA_UseHighDpiPixmaps)
        if hasattr(Qt, 'AA_EnableHighDpiScaling'):
            qapp.setAttribute(Qt.AA_EnableHighDpiScaling,
                              settings.get('high_dpi_scaling'))

        # get the saved window geometry
        window_size = settings.get('MainWindow/size')
        if not isinstance(window_size, QSize):
            window_size = QSize(*window_size)
        window_pos = settings.get('MainWindow/position')
        if not isinstance(window_pos, QPoint):
            window_pos = QPoint(*window_pos)
        if settings.has('MainWindow/font'):
            font_string = settings.get('MainWindow/font').split(',')
            font = QFontDatabase().font(font_string[0], font_string[-1],
                                        int(font_string[1]))
            qapp.setFont(font)

        # make sure main window is smaller than the desktop
        desktop = QDesktopWidget()

        # this gives the maximum screen number if the position is off screen
        screen = desktop.screenNumber(window_pos)

        # recalculate the window size
        desktop_geom = desktop.availableGeometry(screen)
        w = min(desktop_geom.size().width(), window_size.width())
        h = min(desktop_geom.size().height(), window_size.height())
        window_size = QSize(w, h)

        # and position it on the supplied desktop screen
        x = max(window_pos.x(), desktop_geom.left())
        y = max(window_pos.y(), desktop_geom.top())
        if x + w > desktop_geom.right():
            x = desktop_geom.right() - w
        if y + h > desktop_geom.bottom():
            y = desktop_geom.bottom() - h
        window_pos = QPoint(x, y)

        # set the geometry
        self.resize(window_size)
        self.move(window_pos)

        # restore window state
        if settings.has('MainWindow/state'):
            self.restoreState(settings.get('MainWindow/state'))
        else:
            self.setWindowState(Qt.WindowMaximized)

        # read in settings for children
        AlgorithmInputHistory().readSettings(settings)
        for widget in self.widgets:
            if hasattr(widget, 'readSettings'):
                widget.readSettings(settings)
コード例 #15
0
    def load_font(self,
                  prefix,
                  ttf_filename,
                  charmap_filename,
                  directory=None):
        """Loads a font file and the associated charmap

        If `directory` is None, the files will be looked up in ./fonts/

        Arguments
        ---------
        prefix: str
            prefix string to be used when accessing a given font set
        ttf_filename: str
            ttf font filename
        charmap_filename: str
            charmap filename
        directory: str or None, optional
            directory for font and charmap files
        """
        def hook(obj):
            result = {}
            for key in obj:
                result[key] = unichr(int(obj[key], 16))
            return result

        if directory is None:
            directory = os.path.join(
                os.path.dirname(os.path.realpath(__file__)), 'fonts')

        with open(os.path.join(directory, ttf_filename), 'rb') as f:
            font_data = QByteArray(f.read())

        with open(os.path.join(directory, charmap_filename), 'r') as codes:
            self.charmap[prefix] = json.load(codes, object_hook=hook)

        id_ = QFontDatabase.addApplicationFontFromData(font_data)
        loadedFontFamilies = QFontDatabase.applicationFontFamilies(id_)

        if (loadedFontFamilies):
            self.fontname[prefix] = loadedFontFamilies[0]
        else:
            print('Font is empty')
コード例 #16
0
def start_ryven():

    # import windows
    from MainConsole import init_main_console
    from startup_dialog.StartupDialog import StartupDialog
    from MainWindow import MainWindow

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

    # register fonts
    from qtpy.QtGui import QFontDatabase
    db = QFontDatabase()
    db.addApplicationFont('../resources/fonts/poppins/Poppins-Medium.ttf')
    db.addApplicationFont('../resources/fonts/source_code_pro/SourceCodePro-Regular.ttf')
    db.addApplicationFont('../resources/fonts/asap/Asap-Regular.ttf')

    # StartupDialog
    sw = StartupDialog()
    sw.exec_()

    # exit if dialog couldn't initialize
    if sw.editor_startup_configuration == {}:
        sys.exit()

    window_theme = sw.window_theme

    # init main console
    console_stdout_redirect, \
    console_errout_redirect = init_main_console(window_theme)

    # init main window
    mw = MainWindow(sw.editor_startup_configuration, window_theme)
    mw.show()

    if REDIRECT_CONSOLE_OUTPUT:  # redirect console output
        from contextlib import redirect_stdout, redirect_stderr

        with redirect_stdout(console_stdout_redirect), \
                redirect_stderr(console_errout_redirect):

            # run
            mw.print_info()
            sys.exit(app.exec_())

    else:

        # run
        mw.print_info()
        sys.exit(app.exec_())
コード例 #17
0
ファイル: iconic_font.py プロジェクト: zwadar/qtawesome
    def load_font(self, prefix, ttf_filename, charmap_filename, directory=None):
        """Loads a font file and the associated charmap

        If `directory` is None, the files will be looked up in ./fonts/

        Arguments
        ---------
        prefix: str
            prefix string to be used when accessing a given font set
        ttf_filename: str
            ttf font filename
        charmap_filename: str
            charmap filename
        directory: str or None, optional
            directory for font and charmap files
        """

        def hook(obj):
            result = {}
            for key in obj:
                result[key] = unichr(int(obj[key], 16))
            return result

        if directory is None:
            directory = os.path.join(
                os.path.dirname(os.path.realpath(__file__)), 'fonts')

        with open(os.path.join(directory, ttf_filename), 'rb') as f:
            font_data = QByteArray(f.read())

        with open(os.path.join(directory, charmap_filename), 'r') as codes:
            self.charmap[prefix] = json.load(codes, object_hook=hook)

        id_ = QFontDatabase.addApplicationFontFromData(font_data)
        loadedFontFamilies = QFontDatabase.applicationFontFamilies(id_)

        if(loadedFontFamilies):
            self.fontname[prefix] = loadedFontFamilies[0]
        else:
            print('Font is empty')
コード例 #18
0
ファイル: window.py プロジェクト: wsolorza/vidify
    def __init__(self, config: Config) -> None:
        """
        Main window with the GUI and whatever player is being used.
        """

        super().__init__()
        self.setWindowTitle('vidify')

        # Setting the window to stay on top
        if config.stay_on_top:
            self.setWindowFlags(Qt.WindowStaysOnTopHint)

        # Setting the fullscreen and window size
        if config.fullscreen:
            self.showFullScreen()
        else:
            self.setMinimumSize(800, 800)
            self.resize(config.width or 800, config.height or 800)

        # Loading the used fonts (Inter)
        font_db = QFontDatabase()
        for font in Res.fonts:
            font_db.addApplicationFont(font)

        # Initializing the player and saving the config object in the window.
        self.layout = QHBoxLayout(self)
        self.layout.setContentsMargins(0, 0, 0, 0)
        self.layout.setSpacing(0)
        self.config = config

        # Otherwise, the user is prompted for an API. After choosing one,
        # it will be initialized from outside this function.
        logging.info("Loading setup screen")
        self.setup_widget = SetupWidget(config.api, config.player)
        self.layout.addWidget(self.setup_widget)
        self.setup_widget.done.connect(self.on_setup_done)
        # Setting focus on the continue button after the first time.
        if None not in (config.api, config.player):
            self.setup_widget.continue_btn.setFocus()
コード例 #19
0
def main():
    app = QApplication(sys.argv)

    app.setWindowIcon(QIcon(':/icons/app.svg'))

    fontDB = QFontDatabase()
    fontDB.addApplicationFont(':/fonts/Roboto-Regular.ttf')
    app.setFont(QFont('Roboto'))

    f = QFile(':/style.qss')
    f.open(QFile.ReadOnly | QFile.Text)
    app.setStyleSheet(QTextStream(f).readAll())
    f.close()

    translator = QTranslator()
    translator.load(':/translations/' + QLocale.system().name() + '.qm')
    app.installTranslator(translator)

    mw = MainWindow()
    mw.show()

    sys.exit(app.exec_())
コード例 #20
0
    def _init_pyqt(self, exp):

        global app, font_database

        # Add the Qt plugin folders to the library path, if they exists. Where
        # these folders are depends on the version of Qt4, but these are two
        # possible locations.
        qt_plugin_path = os.path.join(os.path.dirname(sys.executable),
                                      'Library', 'plugins')
        if os.path.isdir(qt_plugin_path):
            QCoreApplication.addLibraryPath(
                safe_decode(qt_plugin_path, enc=misc.filesystem_encoding()))
        qt_plugin_path = os.path.join(os.path.dirname(sys.executable),
                                      'Library', 'lib', 'qt4', 'plugins')
        if os.path.isdir(qt_plugin_path):
            QCoreApplication.addLibraryPath(
                safe_decode(qt_plugin_path, enc=misc.filesystem_encoding()))
        # If no instance of QApplication exists, a segmentation fault seems to always
        # occur. So we create one.
        if QCoreApplication.instance() is None:
            app = QApplication([])
        # Register the fonts bundled with OpenSesame
        if font_database is None:
            font_database = QFontDatabase()
            for font in FONTS:
                try:
                    path = exp.resource(font + u'.ttf')
                except:
                    warnings.warn(u'Font %s not found' % font)
                    continue
                font_id = font_database.addApplicationFont(path)
                if font_id < 0:
                    warnings.warn(u'Failed to load font %s' % font)
                    continue
                font_families = font_database.applicationFontFamilies(font_id)
                if not font_families:
                    warnings.warn(u'Font %s contains no families' % font)
                    continue
                font_substitutions.append((font_families[0], font))
コード例 #21
0
 def _init_font(self):
     # There isn't a standard way of getting the system default monospace
     # font in Qt4 (it was introduced in Qt5.2). If QFontDatabase.FixedFont
     # exists, then we can assume that this functionality exists and ask for
     # the correct font directly. Otherwise we ask for a font that doesn't
     # exist and specify our requirements. Qt then finds an existing font
     # that best matches our parameters.
     if hasattr(QFontDatabase, "systemFont") and hasattr(
             QFontDatabase, "FixedFont"):
         font = QFontDatabase.systemFont(QFontDatabase.FixedFont)
     else:
         font = QFont("")
         font.setFixedPitch(True)
         font.setStyleHint(QFont.Monospace)
     self.setFont(font)
コード例 #22
0
ファイル: file_dialog.py プロジェクト: oyvindeide/ert
    def __init__(self,
                 file_name,
                 job_name,
                 job_number,
                 realization,
                 iteration,
                 parent=None):
        super().__init__(parent)

        self.setWindowTitle(
            f"{job_name} # {job_number} "
            f"Realization: {realization} Iteration: {iteration}")

        try:
            self._file = open(file_name, "r")
        except OSError as error:
            self._mb = QMessageBox(
                QMessageBox.Critical,
                "Error opening file",
                error.strerror,
                QMessageBox.Ok,
                self,
            )
            self._mb.finished.connect(self.accept)
            self._mb.show()
            return

        self._view = QPlainTextEdit()
        self._view.setReadOnly(True)
        self._view.setWordWrapMode(QTextOption.NoWrap)
        # for moving the actual slider
        self._view.verticalScrollBar().sliderMoved.connect(self._update_cursor)
        # for mouse wheel and keyboard arrows
        self._view.verticalScrollBar().valueChanged.connect(
            self._update_cursor)

        self._view.setFont(QFontDatabase.systemFont(QFontDatabase.FixedFont))

        self._follow_mode = False

        self._init_layout()
        self._init_thread()

        self.show()
コード例 #23
0
from qtpy.QtCore import Slot, QRegExp
from qtpy.QtGui import QFontDatabase, QRegExpValidator
from qtpy.QtWidgets import QAbstractButton

from qtpyvcp import actions
from qtpyvcp.utilities import logger
from qtpyvcp.widgets.form_widgets.main_window import VCPMainWindow

import probe_basic_rc

LOG = logger.getLogger('QtPyVCP.' + __name__)
VCP_DIR = os.path.abspath(os.path.dirname(__file__))

# Add custom fonts
QFontDatabase.addApplicationFont(os.path.join(VCP_DIR, 'fonts/BebasKai.ttf'))

class ProbeBasic(VCPMainWindow):
    """Main window class for the ProbeBasic VCP."""
    def __init__(self, *args, **kwargs):
        super(ProbeBasic, self).__init__(*args, **kwargs)
        self.run_from_line_Num.setValidator(QRegExpValidator(QRegExp("[0-9]*")))
        self.dynatc_left.iniFilePrefix = "LEFT_"
        self.dynatc_right.iniFilePrefix = "RIGHT_"

    @Slot(QAbstractButton)
    def on_probetabGroup_buttonClicked(self, button):
        self.probe_tab_widget.setCurrentIndex(button.property('page'))

    @Slot(QAbstractButton)
    def on_guiaxisdisplayGroup_buttonClicked(self, button):
コード例 #24
0
    def __init__(self,
                 port: str = None,
                 baudrate: int = None,
                 address: int = None):
        super().__init__()

        #
        # Main window UI
        #

        logging.debug("Initializing MainWindow from mainwindow.ui")
        self.ui = loadUi(dirname(__file__) + "/mainwindow.ui", self)

        logging.debug("Configuring fixed font for labels")
        font = QFontDatabase.systemFont(QFontDatabase.FixedFont)
        font.setBold(True)
        font.setPointSize(36)
        self.ui.voltageInput.setFont(font)
        self.ui.voltageOutput.setFont(font)
        self.ui.currentOutput.setFont(font)
        self.ui.powerOutput.setFont(font)

        logging.debug("Resizing widgets and window to minimum size")
        self.adjustSize()
        self.resize(self.minimumSize())

        #
        # Default value definitions
        #

        # Precition output formats
        # Display formats on real devices
        # Model     V      I       P-on<99W P-on>99W
        # RD6006P   00.000 0.0000  00.000   000.00
        # RD6006    00.00  0.000   00.00    000.0
        # RD6012    00.00  00.00   00.00    000.0
        # RD6018    00.00  00.00   00.00    000.0

        logging.debug("Defining default value definitions")
        self.default_voltage_input_format = "%05.2f"
        self.default_voltage_output_format = "%05.2f"
        self.default_current_output_format = "%05.2f"
        self.default_power_output_format = "%6.2f"
        self.default_voltage_max = 61.0
        self.default_current_max = 0.0

        #
        # QSettings & Setting variables
        #

        logging.debug("Initializing QSettings")
        self.settings = QSettings("ShayBox", "RidenGUI")

        if self.settings.value("first-run", 1) == 1:
            logging.debug("First run detected, showing settings wizard")
            SettingsWizard(self.settings, self).exec()
            exit(0)

        logging.debug("Loading custom format strings from settings")
        self.voltage_input_format = self.settings.value(
            "format/voltage-input", self.default_voltage_input_format)
        self.voltage_output_format = self.settings.value(
            "format/voltage-output", self.default_voltage_output_format)
        self.current_output_format = self.settings.value(
            "format/current-output", self.default_current_output_format)
        self.power_output_format = self.settings.value(
            "format/power-output", self.default_power_output_format)

        logging.debug("Loading custom stylesheets from settings")
        self.output_on = self.settings.value(
            "style/output-on-bg") + self.settings.value("style/output-on-text")
        self.output_off = self.settings.value(
            "style/output-off-bg") + self.settings.value(
                "style/output-off-text")
        self.output_fault = self.settings.value(
            "style/output-fault-bg") + self.settings.value(
                "style/output-fault-text")

        #
        # Riden
        #

        logging.debug("Initializing Riden library")
        self.r = Riden(
            port=port or self.settings.value("serial/port", "/dev/ttyUSB0"),
            baudrate=baudrate
            or int(self.settings.value("serial/baudrate", 115200)),
            address=address or int(self.settings.value("serial/address", 1)),
        )

        logging.debug("Defining temporary variables for live feedback")
        self.prev_v_set = self.r.v_set
        self.prev_i_set = self.r.i_set

        #
        # Dynamic value definitions
        #

        logging.debug("Defining dynamic value definitions")
        if self.r.type == "RD6012":
            self.default_voltage_output_format = "%05.3f"
            self.default_current_output_format = "%05.4f"
            self.default_power_output_format = "%6.3f"
            self.default_current_max = 6.1
        elif self.r.type == "RD6006":
            self.default_current_output_format = "%04.3f"
            self.default_current_max = 6.1
        elif self.r.type == "RD6012":
            self.default_current_max = 12.1
        elif self.r.type == "RD6018":
            self.default_current_max = 18.1
        elif self.r.type == "RD6024":
            self.default_current_max = 24.1

        #
        # Qt Slots, Signals, and Messages
        #

        logging.debug("Connecting signals and slots")
        self.connect_signals()

        logging.debug("Setting permenant statusbar message")
        self.ui.statusbar.showMessage(
            "Connected to %s using %s at %s baud | FW: %s | SN: %s" % (
                self.r.type,
                self.r.serial.port,
                self.r.serial.baudrate,
                self.r.fw,
                self.r.sn,
            ))

        #
        # Background worker
        #

        logging.debug("Starting worker thread")
        self.worker = Worker(self.r, self.settings, self)
        self.worker.update.connect(self.worker_signal)
        self.worker.start()
コード例 #25
0
ファイル: launcher_main.py プロジェクト: Anodarai/PartSeg
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)
    CustomApplication.setAttribute(Qt.AA_EnableHighDpiScaling)
    my_app = CustomApplication(sys.argv, name="PartSeg", icon=os.path.join(icons_dir, "icon.png"))
    my_app.check_release()
    my_app.aboutToQuit.connect(wait_for_workers_to_quit)
    QFontDatabase.addApplicationFont(os.path.join(font_dir, "Symbola.ttf"))
    if args.gui == "roi_analysis" or args.mf:
        from PartSeg import plugins

        plugins.register()
        from PartSeg._roi_analysis.main_window import MainWindow

        title = f"{APP_NAME} {ANALYSIS_NAME}"
        if args.image:
            image = TiffImageReader.read_image(args.image, args.mask)
            MainWindow = partial(MainWindow, initial_image=image)
        wind = MainWindow(title=title)
        if args.batch:
            wind.main_menu.batch_window()
    elif args.gui == "roi_mask":
        from PartSeg import plugins

        plugins.register()
        from PartSeg._roi_mask.main_window import MainWindow

        title = f"{APP_NAME} {MASK_NAME}"
        if args.image:
            image = TiffImageReader.read_image(args.image)
            MainWindow = partial(MainWindow, initial_image=image)
        wind = MainWindow(title=title)
    else:
        from PartSeg._launcher.main_window import MainWindow

        title = f"{APP_NAME} Launcher"
        wind = MainWindow(title=title)

    wind.show()
    rc = my_app.exec_()
    del wind
    del my_app
    sys.exit(rc)
コード例 #26
0
ファイル: iconic_font.py プロジェクト: jules-ch/qtawesome
    def load_font(self,
                  prefix,
                  ttf_filename,
                  charmap_filename,
                  directory=None):
        """Loads a font file and the associated charmap.

        If ``directory`` is None, the files will be looked for in ``./fonts/``.

        Parameters
        ----------
        prefix: str
            Prefix string to be used when accessing a given font set
        ttf_filename: str
            Ttf font filename
        charmap_filename: str
            Charmap filename
        directory: str or None, optional
            Directory for font and charmap files
        """
        def hook(obj):
            result = {}
            for key in obj:
                result[key] = unichr(int(obj[key], 16))
            return result

        if directory is None:
            directory = os.path.join(
                os.path.dirname(os.path.realpath(__file__)), 'fonts')

        # Load font
        if QApplication.instance() is not None:
            id_ = QFontDatabase.addApplicationFont(
                os.path.join(directory, ttf_filename))
            loadedFontFamilies = QFontDatabase.applicationFontFamilies(id_)
            if (loadedFontFamilies):
                self.fontname[prefix] = loadedFontFamilies[0]
            else:
                raise FontError(u"Font at '{0}' appears to be empty. "
                                "If you are on Windows 10, please read "
                                "https://support.microsoft.com/"
                                "en-us/kb/3053676 "
                                "to know how to prevent Windows from blocking "
                                "the fonts that come with QtAwesome.".format(
                                    os.path.join(directory, ttf_filename)))

            with open(os.path.join(directory, charmap_filename), 'r') as codes:
                self.charmap[prefix] = json.load(codes, object_hook=hook)

            # Verify that vendorized fonts are not corrupt
            if not SYSTEM_FONTS:
                md5_hashes = {
                    'fontawesome4.7-webfont.ttf':
                    'b06871f281fee6b241d60582ae9369b9',
                    'fontawesome5-regular-webfont.ttf':
                    '73fe7f1effbf382f499831a0a9f18626',
                    'fontawesome5-solid-webfont.ttf':
                    '0079a0ab6bec4da7d6e16f2a2e87cd71',
                    'fontawesome5-brands-webfont.ttf':
                    '947b9537bc0fecc8130d48eb753495a1',
                    'elusiveicons-webfont.ttf':
                    '207966b04c032d5b873fd595a211582e',
                    'materialdesignicons-webfont.ttf':
                    '64b96825d49e070ea87c7100f2db3f46'
                }
                ttf_hash = md5_hashes.get(ttf_filename, None)
                if ttf_hash is not None:
                    hasher = hashlib.md5()
                    with open(os.path.join(directory, ttf_filename),
                              'rb') as f:
                        content = f.read()
                        hasher.update(content)
                    ttf_calculated_hash_code = hasher.hexdigest()
                    if ttf_calculated_hash_code != ttf_hash:
                        raise FontError(u"Font is corrupt at: '{0}'".format(
                            os.path.join(directory, ttf_filename)))
コード例 #27
0
ファイル: __init__.py プロジェクト: QuQBaZhaHei/search-engine
def load_fonts(app):
    """Load custom fonts."""
    app.database = QFontDatabase()
    for font in FONTFILES:
        app.database.addApplicationFont(font)
コード例 #28
0
    def load_font(self,
                  prefix,
                  ttf_filename,
                  charmap_filename,
                  directory=None):
        """Loads a font file and the associated charmap.

        If ``directory`` is None, the files will be looked for in
        the qtawesome ``fonts`` directory.

        Parameters
        ----------
        prefix: str
            Prefix string to be used when accessing a given font set
        ttf_filename: str
            Ttf font filename
        charmap_filename: str
            Charmap filename
        directory: str or None, optional
            Directory path for font and charmap files
        """
        def hook(obj):
            result = {}
            for key in obj:
                try:
                    result[key] = chr(int(obj[key], 16))
                except ValueError:
                    if int(obj[key], 16) > 0xffff:
                        # ignoring unsupported code in Python 2.7 32bit Windows
                        # ValueError: chr() arg not in range(0x10000)
                        pass
                    else:
                        raise FontError(u'Failed to load character '
                                        '{0}:{1}'.format(key, obj[key]))
            return result

        if directory is None:
            directory = os.path.join(
                os.path.dirname(os.path.realpath(__file__)), 'fonts')

        # Load font
        if QApplication.instance() is not None:
            with open(os.path.join(directory, ttf_filename),
                      'rb') as font_data:
                id_ = QFontDatabase.addApplicationFontFromData(
                    QByteArray(font_data.read()))
            font_data.close()

            loadedFontFamilies = QFontDatabase.applicationFontFamilies(id_)

            if loadedFontFamilies:
                self.fontids[prefix] = id_
                self.fontname[prefix] = loadedFontFamilies[0]
            else:
                raise FontError(u"Font at '{0}' appears to be empty. "
                                "If you are on Windows 10, please read "
                                "https://support.microsoft.com/"
                                "en-us/kb/3053676 "
                                "to know how to prevent Windows from blocking "
                                "the fonts that come with QtAwesome.".format(
                                    os.path.join(directory, ttf_filename)))

            with open(os.path.join(directory, charmap_filename), 'r') as codes:
                self.charmap[prefix] = json.load(codes, object_hook=hook)
コード例 #29
0
    def load_font(self,
                  prefix,
                  ttf_filename,
                  charmap_filename,
                  directory=None):
        """Loads a font file and the associated charmap.

        If ``directory`` is None, the files will be looked for in ``./fonts/``.

        Parameters
        ----------
        prefix: str
            Prefix string to be used when accessing a given font set
        ttf_filename: str
            Ttf font filename
        charmap_filename: str
            Charmap filename
        directory: str or None, optional
            Directory for font and charmap files
        """
        def hook(obj):
            result = {}
            for key in obj:
                result[key] = unichr(int(obj[key], 16))
            return result

        if directory is None:
            directory = os.path.join(
                os.path.dirname(os.path.realpath(__file__)), 'fonts')

        # Load font
        if QApplication.instance() is not None:
            id_ = QFontDatabase.addApplicationFont(
                os.path.join(directory, ttf_filename))
            loadedFontFamilies = QFontDatabase.applicationFontFamilies(id_)
            if (loadedFontFamilies):
                self.fontname[prefix] = loadedFontFamilies[0]
            else:
                raise FontError(u"Font at '{0}' appears to be empty. "
                                "If you are on Windows 10, please read "
                                "https://support.microsoft.com/"
                                "en-us/kb/3053676 "
                                "to know how to prevent Windows from blocking "
                                "the fonts that come with QtAwesome.".format(
                                    os.path.join(directory, ttf_filename)))

            with open(os.path.join(directory, charmap_filename), 'r') as codes:
                self.charmap[prefix] = json.load(codes, object_hook=hook)

            # Verify that vendorized fonts are not corrupt
            if not SYSTEM_FONTS:
                md5_hashes = {
                    'fontawesome4.7-webfont.ttf':
                    'b06871f281fee6b241d60582ae9369b9',
                    'fontawesome5-regular-webfont.ttf':
                    '0e2e26fb3527ae47f9eb1c217592b706',
                    'fontawesome5-solid-webfont.ttf':
                    'e143b57de78138e6d5963908afa7e393',
                    'fontawesome5-brands-webfont.ttf':
                    'dec02372212aab5a2e5294f1a11756ed',
                    'elusiveicons-webfont.ttf':
                    '207966b04c032d5b873fd595a211582e',
                    'materialdesignicons-webfont.ttf':
                    '023db9122f66b7d693bc52bcdf09e6b3'
                }
                ttf_hash = md5_hashes.get(ttf_filename, None)
                if ttf_hash is not None:
                    hasher = hashlib.md5()
                    with open(os.path.join(directory, ttf_filename),
                              'rb') as f:
                        content = f.read()
                        hasher.update(content)
                    ttf_calculated_hash_code = hasher.hexdigest()
                    if ttf_calculated_hash_code != ttf_hash:
                        raise FontError(u"Font is corrupt at: '{0}'".format(
                            os.path.join(directory, ttf_filename)))
コード例 #30
0
ファイル: iconic_font.py プロジェクト: fffoobibi/qtawesome
    def load_font(self,
                  prefix,
                  ttf_filename,
                  charmap_filename,
                  directory=None):
        """Loads a font file and the associated charmap.

        If ``directory`` is None, the files will be looked for in ``./fonts/``.

        Parameters
        ----------
        prefix: str
            Prefix string to be used when accessing a given font set
        ttf_filename: str
            Ttf font filename
        charmap_filename: str
            Charmap filename
        directory: str or None, optional
            Directory for font and charmap files
        """
        def hook(obj):
            result = {}
            for key in obj:
                try:
                    result[key] = chr(int(obj[key], 16))
                except ValueError:
                    if int(obj[key], 16) > 0xffff:
                        # ignoring unsupported code in Python 2.7 32bit Windows
                        # ValueError: chr() arg not in range(0x10000)
                        warnings.warn("Your Python version doesn't support "
                                      "character {0}:{1}".format(
                                          key, obj[key]))
                    else:
                        raise FontError(u'Failed to load character '
                                        '{0}:{1}'.format(key, obj[key]))
            return result

        if directory is None:
            directory = os.path.join(
                os.path.dirname(os.path.realpath(__file__)), 'fonts')

        # Load font
        if QApplication.instance() is not None:
            with open(os.path.join(directory, ttf_filename),
                      'rb') as font_data:
                id_ = QFontDatabase.addApplicationFontFromData(
                    QByteArray(font_data.read()))
            font_data.close()

            loadedFontFamilies = QFontDatabase.applicationFontFamilies(id_)

            if loadedFontFamilies:
                self.fontname[prefix] = loadedFontFamilies[0]
            else:
                raise FontError(u"Font at '{0}' appears to be empty. "
                                "If you are on Windows 10, please read "
                                "https://support.microsoft.com/"
                                "en-us/kb/3053676 "
                                "to know how to prevent Windows from blocking "
                                "the fonts that come with QtAwesome.".format(
                                    os.path.join(directory, ttf_filename)))

            with open(os.path.join(directory, charmap_filename), 'r') as codes:
                self.charmap[prefix] = json.load(codes, object_hook=hook)

            # Verify that vendorized fonts are not corrupt
            if not SYSTEM_FONTS:
                ttf_hash = MD5_HASHES.get(ttf_filename, None)
                if ttf_hash is not None:
                    hasher = hashlib.md5()
                    with open(os.path.join(directory, ttf_filename),
                              'rb') as f:
                        content = f.read()
                        hasher.update(content)
                    ttf_calculated_hash_code = hasher.hexdigest()
                    if ttf_calculated_hash_code != ttf_hash:
                        raise FontError(u"Font is corrupt at: '{0}'".format(
                            os.path.join(directory, ttf_filename)))
コード例 #31
0
    def load_font(self,
                  prefix,
                  ttf_filename,
                  charmap_filename,
                  directory=None):
        """Loads a font file and the associated charmap.

        If ``directory`` is None, the files will be looked for in ``./fonts/``.

        Parameters
        ----------
        prefix: str
            Prefix string to be used when accessing a given font set
        ttf_filename: str
            Ttf font filename
        charmap_filename: str
            Charmap filename
        directory: str or None, optional
            Directory for font and charmap files
        """
        def hook(obj):
            result = {}
            for key in obj:
                result[key] = unichr(int(obj[key], 16))
            return result

        if directory is None:
            directory = os.path.join(
                os.path.dirname(os.path.realpath(__file__)), 'fonts')

        # Load font
        if QApplication.instance() is not None:
            id_ = QFontDatabase.addApplicationFont(
                os.path.join(directory, ttf_filename))
            loadedFontFamilies = QFontDatabase.applicationFontFamilies(id_)
            if (loadedFontFamilies):
                self.fontname[prefix] = loadedFontFamilies[0]
            else:
                raise FontError(u"Font at '{0}' appears to be empty. "
                                "If you are on Windows 10, please read "
                                "https://support.microsoft.com/"
                                "en-us/kb/3053676 "
                                "to know how to prevent Windows from blocking "
                                "the fonts that come with QtAwesome.".format(
                                    os.path.join(directory, ttf_filename)))

            with open(os.path.join(directory, charmap_filename), 'r') as codes:
                self.charmap[prefix] = json.load(codes, object_hook=hook)

            # Verify that vendorized fonts are not corrupt
            if not SYSTEM_FONTS:
                md5_hashes = {
                    'fontawesome-webfont.ttf':
                    'a3de2170e4e9df77161ea5d3f31b2668',
                    'elusiveicons-webfont.ttf':
                    '207966b04c032d5b873fd595a211582e'
                }
                ttf_hash = md5_hashes.get(ttf_filename, None)
                if ttf_hash is not None:
                    hasher = hashlib.md5()
                    with open(os.path.join(directory, ttf_filename),
                              'rb') as f:
                        content = f.read()
                        hasher.update(content)
                    ttf_calculated_hash_code = hasher.hexdigest()
                    if ttf_calculated_hash_code != ttf_hash:
                        raise FontError(u"Font is corrupt at: '{0}'".format(
                            os.path.join(directory, ttf_filename)))
コード例 #32
0
def font_is_installed(font):
    """Check if font is installed"""
    return [fam for fam in QFontDatabase().families()
            if to_text_string(fam)==font]
コード例 #33
0
    def __init__(self, filetype, filename):
        super().__init__()

        from db.BiblesSqlite import Bible
        self.fontDatabase = QFontDatabase()

        self.filetype = filetype
        self.filename = filename

        self.setWindowTitle(config.thisTranslation["modify_database"])
        self.layout = QVBoxLayout()
        self.setMinimumWidth(300)

        if filetype == "bible":
            self.bible = Bible(filename)
            self.bible.addMissingColumns()
            (fontName, fontSize, css) = self.bible.getFontInfo()
            if fontName is None:
                fontName = ""
            if fontSize is None:
                fontSize = ""

            self.layout.addWidget(
                QLabel("{0}: {1}".format(config.thisTranslation["name"],
                                         filename)))

            row = QHBoxLayout()
            row.addWidget(
                QLabel("{0}: ".format(config.thisTranslation["title"])))
            self.bibleTitle = QLineEdit()
            self.bibleTitle.setText(self.bible.bibleInfo())
            self.bibleTitle.setMaxLength(100)
            row.addWidget(self.bibleTitle)
            self.layout.addLayout(row)

            grid = QGridLayout()

            self.builtinFonts = [""] + self.fontDatabase.families()
            try:
                index = self.builtinFonts.index(
                    fontName.replace(".builtin", ""))
            except:
                index = 0
            self.useBuiltinFont = QRadioButton()
            self.useBuiltinFont.clicked.connect(
                lambda: self.selectRadio("builtin"))
            grid.addWidget(self.useBuiltinFont, 0, 0)
            grid.addWidget(QLabel("{0}: ".format("Built-in font")), 0, 1)
            self.builtinFontList = QComboBox()
            self.builtinFontList.addItems(self.builtinFonts)
            self.builtinFontList.setCurrentIndex(index)
            grid.addWidget(self.builtinFontList, 0, 2)

            fonts = sorted(glob.glob(r"htmlResources/fonts/*.*"))
            self.fontFiles = [''] + [os.path.basename(font) for font in fonts]
            try:
                index = self.fontFiles.index(fontName)
            except:
                index = 0
            row = QHBoxLayout()
            self.useFileFont = QRadioButton()
            self.useFileFont.clicked.connect(lambda: self.selectRadio("file"))
            grid.addWidget(self.useFileFont, 1, 0)
            row.addStretch(1)
            grid.addWidget(QLabel("{0}: ".format("Font file")), 1, 1)
            self.fileFontList = QComboBox()
            self.fileFontList.addItems(self.fontFiles)
            self.fileFontList.setCurrentIndex(index)
            grid.addWidget(self.fileFontList, 1, 2)
            self.layout.addLayout(grid)
        else:
            self.layout.addWidget(
                QLabel("{0} is not supported".format(filetype)))

        row = QHBoxLayout()
        row.addWidget(
            QLabel("{0}: ".format(config.thisTranslation["menu2_fontSize"])))
        self.fontSize = QLineEdit()
        self.fontSize.setText(fontSize)
        self.fontSize.setMaxLength(20)
        row.addWidget(self.fontSize)
        self.layout.addLayout(row)

        self.languageCodes = [""
                              ] + [value for value in Languages.code.values()]

        row = QHBoxLayout()
        row.addWidget(
            QLabel("{0}: ".format(config.thisTranslation["menu_language"])))
        self.languageList = QComboBox()
        row.addWidget(self.languageList)
        self.languageList.addItems(self.languageCodes)
        self.languageList.setCurrentIndex(
            self.languageCodes.index(self.bible.getLanguage()))
        self.layout.addLayout(row)

        buttons = QDialogButtonBox.Ok | QDialogButtonBox.Cancel
        self.buttonBox = QDialogButtonBox(buttons)
        self.buttonBox.accepted.connect(self.save)
        self.buttonBox.accepted.connect(self.accept)
        self.buttonBox.rejected.connect(self.reject)
        self.layout.addWidget(self.buttonBox)
        self.setLayout(self.layout)

        if ".ttf" in fontName:
            self.selectRadio("file")
        else:
            self.selectRadio("builtin")