Example #1
0
class BlockingBusy(QDialog):

    def __init__(self, msg, parent=None, window_title=_('Working')):
        QDialog.__init__(self, parent)

        self._layout = QVBoxLayout()
        self.setLayout(self._layout)
        self.msg = QLabel(msg)
        #self.msg.setWordWrap(True)
        self.font = QFont()
        self.font.setPointSize(self.font.pointSize() + 8)
        self.msg.setFont(self.font)
        self.pi = ProgressIndicator(self)
        self.pi.setDisplaySize(100)
        self._layout.addWidget(self.pi, 0, Qt.AlignHCenter)
        self._layout.addSpacing(15)
        self._layout.addWidget(self.msg, 0, Qt.AlignHCenter)
        self.start()
        self.setWindowTitle(window_title)
        self.resize(self.sizeHint())

    def start(self):
        self.pi.startAnimation()

    def stop(self):
        self.pi.stopAnimation()

    def accept(self):
        self.stop()
        return QDialog.accept(self)

    def reject(self):
        pass # Cannot cancel this dialog
Example #2
0
    def __init__(self, parent, recipe_model):
        ResizableDialog.__init__(self, parent)

        self._model = self.model = CustomRecipeModel(recipe_model)
        self.available_profiles.setModel(self._model)
        self.available_profiles.currentChanged = self.current_changed
        f = QFont()
        f.setStyleHint(f.Monospace)
        self.source_code.setFont(f)

        self.remove_feed_button.clicked[(bool)].connect(
            self.added_feeds.remove_selected_items)
        self.remove_profile_button.clicked[(bool)].connect(
            self.remove_selected_items)
        self.add_feed_button.clicked[(bool)].connect(self.add_feed)
        self.load_button.clicked[()].connect(self.load)
        self.opml_button.clicked[()].connect(self.opml_import)
        self.builtin_recipe_button.clicked[()].connect(self.add_builtin_recipe)
        self.share_button.clicked[()].connect(self.share)
        self.show_recipe_files_button.clicked.connect(self.show_recipe_files)
        self.down_button.clicked[()].connect(self.down)
        self.up_button.clicked[()].connect(self.up)
        self.add_profile_button.clicked[(bool)].connect(self.add_profile)
        self.feed_url.returnPressed[()].connect(self.add_feed)
        self.feed_title.returnPressed[()].connect(self.add_feed)
        self.toggle_mode_button.clicked[(bool)].connect(self.toggle_mode)
        self.clear()
Example #3
0
class BlockingBusy(QDialog):
    def __init__(self, msg, parent=None, window_title=_('Working')):
        QDialog.__init__(self, parent)

        self._layout = QVBoxLayout()
        self.setLayout(self._layout)
        self.msg = QLabel(msg)
        #self.msg.setWordWrap(True)
        self.font = QFont()
        self.font.setPointSize(self.font.pointSize() + 8)
        self.msg.setFont(self.font)
        self.pi = ProgressIndicator(self)
        self.pi.setDisplaySize(100)
        self._layout.addWidget(self.pi, 0, Qt.AlignHCenter)
        self._layout.addSpacing(15)
        self._layout.addWidget(self.msg, 0, Qt.AlignHCenter)
        self.start()
        self.setWindowTitle(window_title)
        self.resize(self.sizeHint())

    def start(self):
        self.pi.startAnimation()

    def stop(self):
        self.pi.stopAnimation()

    def accept(self):
        self.stop()
        return QDialog.accept(self)

    def reject(self):
        pass  # Cannot cancel this dialog
Example #4
0
 def apply_theme(self, theme):
     self.theme = theme
     pal = self.palette()
     pal.setColor(pal.Base, theme_color(theme, 'Normal', 'bg'))
     pal.setColor(pal.AlternateBase, theme_color(theme, 'CursorLine', 'bg'))
     pal.setColor(pal.Text, theme_color(theme, 'Normal', 'fg'))
     pal.setColor(pal.Highlight, theme_color(theme, 'Visual', 'bg'))
     pal.setColor(pal.HighlightedText, theme_color(theme, 'Visual', 'fg'))
     self.setPalette(pal)
     self.tooltip_palette = pal = QPalette()
     pal.setColor(pal.ToolTipBase, theme_color(theme, 'Tooltip', 'bg'))
     pal.setColor(pal.ToolTipText, theme_color(theme, 'Tooltip', 'fg'))
     self.line_number_palette = pal = QPalette()
     pal.setColor(pal.Base, theme_color(theme, 'LineNr', 'bg'))
     pal.setColor(pal.Text, theme_color(theme, 'LineNr', 'fg'))
     pal.setColor(pal.BrightText, theme_color(theme, 'LineNrC', 'fg'))
     self.match_paren_format = theme_format(theme, 'MatchParen')
     font = self.font()
     ff = tprefs['editor_font_family']
     if ff is None:
         ff = default_font_family()
     font.setFamily(ff)
     font.setPointSize(tprefs['editor_font_size'])
     self.tooltip_font = QFont(font)
     self.tooltip_font.setPointSize(font.pointSize() - 1)
     self.setFont(font)
     self.highlighter.apply_theme(theme)
     w = self.fontMetrics()
     self.number_width = max(map(lambda x: w.width(str(x)), xrange(10)))
     self.size_hint = QSize(100 * w.averageCharWidth(), 50 * w.height())
     self.highlight_color = theme_color(theme, 'HighlightRegion', 'bg')
     self.highlight_cursor_line()
Example #5
0
    def paint_line_numbers(self, ev):
        painter = QPainter(self.line_number_area)
        painter.fillRect(ev.rect(),
                         self.line_number_palette.color(QPalette.Base))

        block = self.firstVisibleBlock()
        num = block.blockNumber()
        top = int(
            self.blockBoundingGeometry(block).translated(
                self.contentOffset()).top())
        bottom = top + int(self.blockBoundingRect(block).height())
        current = self.textCursor().block().blockNumber()
        painter.setPen(self.line_number_palette.color(QPalette.Text))

        while block.isValid() and top <= ev.rect().bottom():
            if block.isVisible() and bottom >= ev.rect().top():
                if current == num:
                    painter.save()
                    painter.setPen(
                        self.line_number_palette.color(QPalette.BrightText))
                    f = QFont(self.font())
                    f.setBold(True)
                    painter.setFont(f)
                    self.last_current_lnum = (top, bottom - top)
                painter.drawText(0, top,
                                 self.line_number_area.width() - 5,
                                 self.fontMetrics().height(), Qt.AlignRight,
                                 str(num + 1))
                if current == num:
                    painter.restore()
            block = block.next()
            top = bottom
            bottom = top + int(self.blockBoundingRect(block).height())
            num += 1
Example #6
0
class RatingDelegate(QStyledItemDelegate):  # {{{
    def __init__(self, *args, **kwargs):
        QStyledItemDelegate.__init__(self, *args, **kwargs)
        self.rf = QFont(rating_font())
        self.em = Qt.ElideMiddle
        delta = 0
        if iswindows and sys.getwindowsversion().major >= 6:
            delta = 2
        self.rf.setPointSize(
            QFontInfo(QApplication.font()).pointSize() + delta)

    def createEditor(self, parent, option, index):
        sb = QStyledItemDelegate.createEditor(self, parent, option, index)
        sb.setMinimum(0)
        sb.setMaximum(5)
        sb.setSuffix(' ' + _('stars'))
        return sb

    def displayText(self, value, locale):
        r = value.toInt()[0]
        if r < 0 or r > 5:
            r = 0
        return u'\u2605' * r

    def sizeHint(self, option, index):
        option.font = self.rf
        option.textElideMode = self.em
        return QStyledItemDelegate.sizeHint(self, option, index)

    def paint(self, painter, option, index):
        option.font = self.rf
        option.textElideMode = self.em
        return QStyledItemDelegate.paint(self, painter, option, index)
Example #7
0
class RatingDelegate(QStyledItemDelegate):  # {{{

    def __init__(self, *args, **kwargs):
        QStyledItemDelegate.__init__(self, *args, **kwargs)
        self.rf = QFont(rating_font())
        self.em = Qt.ElideMiddle
        delta = 0
        if iswindows and sys.getwindowsversion().major >= 6:
            delta = 2
        self.rf.setPointSize(QFontInfo(QApplication.font()).pointSize()+delta)

    def createEditor(self, parent, option, index):
        sb = QStyledItemDelegate.createEditor(self, parent, option, index)
        sb.setMinimum(0)
        sb.setMaximum(5)
        sb.setSuffix(' ' + _('stars'))
        return sb

    def displayText(self, value, locale):
        r = value.toInt()[0]
        if r < 0 or r > 5:
            r = 0
        return u'\u2605'*r

    def sizeHint(self, option, index):
        option.font = self.rf
        option.textElideMode = self.em
        return QStyledItemDelegate.sizeHint(self, option, index)

    def paint(self, painter, option, index):
        option.font = self.rf
        option.textElideMode = self.em
        return QStyledItemDelegate.paint(self, painter, option, index)
Example #8
0
 def __init__(self, spine, toc, depth, all_items, parent=None):
     text = toc.text
     if text:
         text = re.sub(r'\s', ' ', text)
     self.title = text
     self.parent = parent
     QStandardItem.__init__(self, text if text else '')
     self.abspath = toc.abspath if toc.href else None
     self.fragment = toc.fragment
     all_items.append(self)
     self.bold_font = QFont(self.font())
     self.bold_font.setBold(True)
     self.normal_font = self.font()
     for t in toc:
         self.appendRow(TOCItem(spine, t, depth+1, all_items, parent=self))
     self.setFlags(Qt.ItemIsEnabled)
     spos = 0
     for i, si in enumerate(spine):
         if si == self.abspath:
             spos = i
             break
     am = {}
     if self.abspath is not None:
         try:
             am = getattr(spine[i], 'anchor_map', {})
         except UnboundLocalError:
             # Spine was empty?
             pass
     frag = self.fragment if (self.fragment and self.fragment in am) else None
     self.starts_at = spos
     self.start_anchor = frag
     self.start_src_offset = am.get(frag, 0)
     self.depth = depth
     self.is_being_viewed = False
Example #9
0
    def __init__(self, name, plugins, gui_name, parent=None):
        QWidget.__init__(self, parent)
        self._layout = QVBoxLayout()
        self.setLayout(self._layout)
        self.label = QLabel(gui_name)
        self.sep = QFrame(self)
        self.bf = QFont()
        self.bf.setBold(True)
        self.label.setFont(self.bf)
        self.sep.setFrameShape(QFrame.HLine)
        self._layout.addWidget(self.label)
        self._layout.addWidget(self.sep)

        self.plugins = plugins

        self.bar = QToolBar(self)
        self.bar.setStyleSheet(
                'QToolBar { border: none; background: none }')
        self.bar.setIconSize(QSize(32, 32))
        self.bar.setMovable(False)
        self.bar.setFloatable(False)
        self.bar.setToolButtonStyle(Qt.ToolButtonTextUnderIcon)
        self._layout.addWidget(self.bar)
        self.actions = []
        for p in plugins:
            target = partial(self.triggered, p)
            ac = self.bar.addAction(QIcon(p.icon), p.gui_name, target)
            ac.setToolTip(textwrap.fill(p.description))
            ac.setWhatsThis(textwrap.fill(p.description))
            ac.setStatusTip(p.description)
            self.actions.append(ac)
            w = self.bar.widgetForAction(ac)
            w.setCursor(Qt.PointingHandCursor)
            w.setAutoRaise(True)
            w.setMinimumWidth(100)
Example #10
0
    def __init__(self, args, ids, db, refresh_books, cc_widgets, s_r_func, do_sr, sr_calls, parent=None, window_title=_('Working')):
        QDialog.__init__(self, parent)

        self._layout =  l = QVBoxLayout()
        self.setLayout(l)

        self.msg = QLabel(_('Processing %d books, please wait...') % len(ids))
        self.font = QFont()
        self.font.setPointSize(self.font.pointSize() + 8)
        self.msg.setFont(self.font)
        self.pi = ProgressIndicator(self)
        self.pi.setDisplaySize(100)
        self._layout.addWidget(self.pi, 0, Qt.AlignHCenter)
        self._layout.addSpacing(15)
        self._layout.addWidget(self.msg, 0, Qt.AlignHCenter)
        self.setWindowTitle(window_title + '...')
        self.setMinimumWidth(200)
        self.resize(self.sizeHint())
        self.error = None
        self.all_done.connect(self.on_all_done, type=Qt.QueuedConnection)
        self.args, self.ids = args, ids
        self.db, self.cc_widgets = db, cc_widgets
        self.s_r_func = FunctionDispatcher(s_r_func)
        self.do_sr = do_sr
        self.sr_calls = sr_calls
        self.refresh_books = refresh_books
Example #11
0
    def setup_styles(self, force_calibre_style):
        self.original_font = QFont(QApplication.font())
        fi = gprefs['font']
        if fi is not None:
            font = QFont(*(fi[:4]))
            s = gprefs.get('font_stretch', None)
            if s is not None:
                font.setStretch(s)
            QApplication.setFont(font)

        depth_ok = True
        if iswindows:
            # There are some people that still run 16 bit winxp installs. The
            # new style does not render well on 16bit machines.
            try:
                depth_ok = get_windows_color_depth() >= 32
            except:
                import traceback
                traceback.print_exc()

        if force_calibre_style or (depth_ok
                                   and gprefs['ui_style'] != 'system'):
            self.load_calibre_style()
        else:
            st = self.style()
            if st is not None:
                st = unicode(st.objectName()).lower()
            if (islinux or isbsd) and st in ('windows', 'motif', 'cde'):
                from PyQt4.Qt import QStyleFactory
                styles = set(map(unicode, QStyleFactory.keys()))
                if os.environ.get('KDE_FULL_SESSION', False):
                    self.load_calibre_style()
                elif 'Cleanlooks' in styles:
                    self.setStyle('Cleanlooks')
Example #12
0
    def __init__(self, parent, recipe_model):
        ResizableDialog.__init__(self, parent)

        self._model = self.model = CustomRecipeModel(recipe_model)
        self.available_profiles.setModel(self._model)
        self.available_profiles.currentChanged = self.current_changed
        f = QFont()
        f.setStyleHint(f.Monospace)
        self.source_code.setFont(f)

        self.remove_feed_button.clicked[(bool)].connect(self.added_feeds.remove_selected_items)
        self.remove_profile_button.clicked[(bool)].connect(self.remove_selected_items)
        self.add_feed_button.clicked[(bool)].connect(self.add_feed)
        self.load_button.clicked[()].connect(self.load)
        self.opml_button.clicked[()].connect(self.opml_import)
        self.builtin_recipe_button.clicked[()].connect(self.add_builtin_recipe)
        self.share_button.clicked[()].connect(self.share)
        self.show_recipe_files_button.clicked.connect(self.show_recipe_files)
        self.down_button.clicked[()].connect(self.down)
        self.up_button.clicked[()].connect(self.up)
        self.add_profile_button.clicked[(bool)].connect(self.add_profile)
        self.feed_url.returnPressed[()].connect(self.add_feed)
        self.feed_title.returnPressed[()].connect(self.add_feed)
        self.toggle_mode_button.clicked[(bool)].connect(self.toggle_mode)
        self.clear()
Example #13
0
 def __init__(self, parent, emphasize=False):
     QComboBox.__init__(self)
     self.addItems([
         _('Current file'),
         _('All text files'),
         _('All style files'),
         _('Selected files'),
         _('Marked text')
     ])
     self.setToolTip('<style>dd {margin-bottom: 1.5ex}</style>' + _('''
         Where to search/replace:
         <dl>
         <dt><b>Current file</b></dt>
         <dd>Search only inside the currently opened file</dd>
         <dt><b>All text files</b></dt>
         <dd>Search in all text (HTML) files</dd>
         <dt><b>All style files</b></dt>
         <dd>Search in all style (CSS) files</dd>
         <dt><b>Selected files</b></dt>
         <dd>Search in the files currently selected in the Files Browser</dd>
         <dt><b>Marked text</b></dt>
         <dd>Search only within the marked text in the currently opened file. You can mark text using the Search menu.</dd>
         </dl>'''))
     self.emphasize = emphasize
     self.ofont = QFont(self.font())
     if emphasize:
         f = self.emph_font = QFont(self.ofont)
         f.setBold(True), f.setItalic(True)
         self.setFont(f)
Example #14
0
    def paint_line_numbers(self, ev):
        painter = QPainter(self.line_number_area)
        painter.fillRect(ev.rect(), self.line_number_palette.color(QPalette.Base))

        block = self.firstVisibleBlock()
        num = block.blockNumber()
        top = int(self.blockBoundingGeometry(block).translated(self.contentOffset()).top())
        bottom = top + int(self.blockBoundingRect(block).height())
        current = self.textCursor().block().blockNumber()
        painter.setPen(self.line_number_palette.color(QPalette.Text))

        while block.isValid() and top <= ev.rect().bottom():
            if block.isVisible() and bottom >= ev.rect().top():
                if current == num:
                    painter.save()
                    painter.setPen(self.line_number_palette.color(QPalette.BrightText))
                    f = QFont(self.font())
                    f.setBold(True)
                    painter.setFont(f)
                    self.last_current_lnum = (top, bottom - top)
                painter.drawText(0, top, self.line_number_area.width() - 5, self.fontMetrics().height(),
                              Qt.AlignRight, str(num + 1))
                if current == num:
                    painter.restore()
            block = block.next()
            top = bottom
            bottom = top + int(self.blockBoundingRect(block).height())
            num += 1
Example #15
0
 def _initFonts():
     """Initializes fonts on fitrst call"""
     if SkyModelTreeWidgetItem._fonts is None:
         stdfont = QApplication.font()
         boldfont = QFont(stdfont)
         boldfont.setBold(True)
         SkyModelTreeWidgetItem._fonts = [stdfont, boldfont]
         SkyModelTreeWidgetItem._fontmetrics = QFontMetrics(boldfont)
Example #16
0
 def build_font_obj(self):
     font_info = self.current_font
     if font_info is not None:
         font = QFont(*(font_info[:4]))
         font.setStretch(font_info[4])
     else:
         font = qt_app.original_font
     return font
Example #17
0
 def capture_clicked(self, which=1):
     self.capture = which
     button = getattr(self, 'button%d' % which)
     button.setText(_('Press a key...'))
     button.setFocus(Qt.OtherFocusReason)
     font = QFont()
     font.setBold(True)
     button.setFont(font)
Example #18
0
 def getLabelFont(self, isBold=False):
     """
     Returns the font for the labels in the grid
     """
     # Font for labels.
     labelFont = QFont(self.font())
     labelFont.setBold(False)
     return labelFont
 def _getFontForTextNearCursor(self, fontSize = 10, isBold = False):
     """
     Returns the font for text near the cursor. 
     @see: self.renderTextNearCursor
     """
     font = QFont("Arial", fontSize)
     font.setBold(isBold)              
     return font
Example #20
0
 def _initFonts():
     """Initializes fonts on fitrst call"""
     if SkyModelTreeWidgetItem._fonts is None:
         stdfont = QApplication.font()
         boldfont = QFont(stdfont)
         boldfont.setBold(True)
         SkyModelTreeWidgetItem._fonts = [stdfont, boldfont]
         SkyModelTreeWidgetItem._fontmetrics = QFontMetrics(boldfont)
Example #21
0
 def getLabelFont(self, isBold = False):
     """
     Returns the font for the labels in the grid
     """
     # Font for labels.
     labelFont = QFont(self.font())
     labelFont.setBold(False)
     return labelFont
Example #22
0
 def __init__(self, *args, **kwargs):
     QStyledItemDelegate.__init__(self, *args, **kwargs)
     self.rf = QFont(rating_font())
     self.em = Qt.ElideMiddle
     delta = 0
     if iswindows and sys.getwindowsversion().major >= 6:
         delta = 2
     self.rf.setPointSize(QFontInfo(QApplication.font()).pointSize()+delta)
Example #23
0
    def __init__(self, shortcuts, parent=None):
        QDialog.__init__(self, parent)
        self.setupUi(self)

        opts = config().parse()
        self.opt_remember_window_size.setChecked(opts.remember_window_size)
        self.opt_remember_current_page.setChecked(opts.remember_current_page)
        self.opt_wheel_flips_pages.setChecked(opts.wheel_flips_pages)
        self.opt_page_flip_duration.setValue(opts.page_flip_duration)
        fms = opts.font_magnification_step
        if fms < 0.01 or fms > 1:
            fms = 0.2
        self.opt_font_mag_step.setValue(int(fms * 100))
        self.opt_line_scrolling_stops_on_pagebreaks.setChecked(
            opts.line_scrolling_stops_on_pagebreaks)
        self.serif_family.setCurrentFont(QFont(opts.serif_family))
        self.sans_family.setCurrentFont(QFont(opts.sans_family))
        self.mono_family.setCurrentFont(QFont(opts.mono_family))
        self.default_font_size.setValue(opts.default_font_size)
        self.mono_font_size.setValue(opts.mono_font_size)
        self.standard_font.setCurrentIndex({
            'serif': 0,
            'sans': 1,
            'mono': 2
        }[opts.standard_font])
        self.css.setPlainText(opts.user_css)
        self.css.setToolTip(
            _('Set the user CSS stylesheet. This can be used to customize the look of all books.'
              ))
        self.max_fs_width.setValue(opts.max_fs_width)
        with zipfile.ZipFile(
                P('viewer/hyphenate/patterns.zip', allow_user_override=False),
                'r') as zf:
            pats = [x.split('.')[0].replace('-', '_') for x in zf.namelist()]
        names = list(map(get_language, pats))
        pmap = {}
        for i in range(len(pats)):
            pmap[names[i]] = pats[i]
        for x in sorted(names):
            self.hyphenate_default_lang.addItem(x, QVariant(pmap[x]))
        try:
            idx = pats.index(opts.hyphenate_default_lang)
        except ValueError:
            idx = pats.index('en_us')
        idx = self.hyphenate_default_lang.findText(names[idx])
        self.hyphenate_default_lang.setCurrentIndex(idx)
        self.hyphenate.setChecked(opts.hyphenate)
        self.hyphenate_default_lang.setEnabled(opts.hyphenate)
        self.shortcuts = shortcuts
        self.shortcut_config = ShortcutConfig(shortcuts, parent=self)
        p = self.tabs.widget(1)
        p.layout().addWidget(self.shortcut_config)
        self.opt_fit_images.setChecked(opts.fit_images)
        if isxp:
            self.hyphenate.setVisible(False)
            self.hyphenate_default_lang.setVisible(False)
            self.hyphenate_label.setVisible(False)
        self.opt_fullscreen_clock.setChecked(opts.fullscreen_clock)
Example #24
0
class HeaderView(QHeaderView):  # {{{
    def __init__(self, *args):
        QHeaderView.__init__(self, *args)
        self.hover = -1
        self.current_font = QFont(self.font())
        self.current_font.setBold(True)
        self.current_font.setItalic(True)

    def event(self, e):
        if e.type() in (e.HoverMove, e.HoverEnter):
            self.hover = self.logicalIndexAt(e.pos())
        elif e.type() in (e.Leave, e.HoverLeave):
            self.hover = -1
        return QHeaderView.event(self, e)

    def paintSection(self, painter, rect, logical_index):
        opt = QStyleOptionHeader()
        self.initStyleOption(opt)
        opt.rect = rect
        opt.section = logical_index
        opt.orientation = self.orientation()
        opt.textAlignment = Qt.AlignHCenter | Qt.AlignVCenter
        model = self.parent().model()
        opt.text = model.headerData(logical_index, opt.orientation,
                                    Qt.DisplayRole).toString()
        if self.isSortIndicatorShown() and self.sortIndicatorSection(
        ) == logical_index:
            opt.sortIndicator = QStyleOptionHeader.SortDown if self.sortIndicatorOrder(
            ) == Qt.AscendingOrder else QStyleOptionHeader.SortUp
        opt.text = opt.fontMetrics.elidedText(opt.text, Qt.ElideRight,
                                              rect.width() - 4)
        if self.isEnabled():
            opt.state |= QStyle.State_Enabled
            if self.window().isActiveWindow():
                opt.state |= QStyle.State_Active
                if self.hover == logical_index:
                    opt.state |= QStyle.State_MouseOver
        sm = self.selectionModel()
        if opt.orientation == Qt.Vertical:
            try:
                opt.icon = model.headerData(logical_index, opt.orientation,
                                            Qt.DecorationRole)
                opt.iconAlignment = Qt.AlignVCenter
            except (IndexError, ValueError, TypeError):
                pass
            if sm.isRowSelected(logical_index, QModelIndex()):
                opt.state |= QStyle.State_Sunken

        painter.save()
        if ((opt.orientation == Qt.Horizontal
             and sm.currentIndex().column() == logical_index)
                or (opt.orientation == Qt.Vertical
                    and sm.currentIndex().row() == logical_index)):
            painter.setFont(self.current_font)
        self.style().drawControl(QStyle.CE_Header, opt, painter, self)
        painter.restore()
Example #25
0
 def paintEvent(self, ev):
     # We do it like this so that the popup uses a normal font
     if self.emphasize:
         ofont = self.font()
         f = QFont(ofont)
         f.setBold(True), f.setItalic(True)
         self.setFont(f)
     QComboBox.paintEvent(self, ev)
     if self.emphasize:
         self.setFont(ofont)
Example #26
0
 def __init__(self):
     self.labels_font = QFont('Verdana', 10)
     self.helper_font = self.labels_font
     self.helpers_color = QColor(0, 0, 0, 255)
     self.background_color = QColor(255, 255, 255, 255)
     self.axis_title_font = QFont('Verdana', 11, QFont.Bold)
     self.axis_font = QFont('Verdana', 10)
     self.labels_color = QColor(0, 0, 0, 255)
     self.axis_color = QColor(30, 30, 30, 255)
     self.axis_values_color = QColor(30, 30, 30, 255)
Example #27
0
 def set_preferred_country(self):
     item = self.dictionaries.currentItem()
     bf = QFont(self.dictionaries.font())
     bf.setBold(True)
     for x in (item.parent().child(i) for i in xrange(item.parent().childCount())):
         x.setData(0, Qt.FontRole, bf if x is item else None)
     lc = unicode(item.parent().data(0, Qt.UserRole).toPyObject())
     pl = dprefs['preferred_locales']
     pl[lc] = '%s-%s' % (lc, unicode(item.data(0, Qt.UserRole).toPyObject()))
     dprefs['preferred_locales'] = pl
 def setUpItemsTable(self):
     rowsFont = QFont('Lucida', 12, QtGui.QFont.Bold)
     self.ItemTable.setFont(rowsFont)
     headerFont = QFont('Lucida', 12, QtGui.QFont.Bold)
     self.ItemTable.setFont(rowsFont)
     self.ItemTable.horizontalHeader().setFont(headerFont)
     self.ItemTable.horizontalHeader().setResizeMode(
         0, QHeaderView.ResizeToContents)
     self.ItemTable.horizontalHeader().setResizeMode(1, QHeaderView.Stretch)
     self.ItemTable.horizontalHeader().setResizeMode(2, QHeaderView.Stretch)
     self.ItemTable.verticalHeader().hide()
     self._fillItemsTable()
Example #29
0
    def __init__(self, parent, icon_name, title):
        QHBoxLayout.__init__(self)
        self.title_image_label = QLabel(parent)
        self.update_title_icon(icon_name)
        self.addWidget(self.title_image_label)

        title_font = QFont()
        title_font.setPointSize(16)
        shelf_label = QLabel(title, parent)
        shelf_label.setFont(title_font)
        self.addWidget(shelf_label)
        self.insertStretch(-1)
Example #30
0
    def __init__(self, parent=None):
        QStatusBar.__init__(self, parent)
        self.default_message = __appname__ + ' ' + _('version') + ' ' + \
                __version__ + ' ' + _('created by Kovid Goyal')
        self.device_string = ''
        self._font = QFont()
        self._font.setBold(True)
        self.setFont(self._font)

        self.w = QLabel(self.default_message)
        self.w.setFont(self._font)
        self.addWidget(self.w)
Example #31
0
    def __init__(self, parent, icon_name, title):
        QHBoxLayout.__init__(self)
        self.title_image_label = QLabel(parent)
        self.update_title_icon(icon_name)
        self.addWidget(self.title_image_label)

        title_font = QFont()
        title_font.setPointSize(16)
        shelf_label = QLabel(title, parent)
        shelf_label.setFont(title_font)
        self.addWidget(shelf_label)
        self.insertStretch(-1)
Example #32
0
 def set_window_title(self):
     db = self.current_db
     restrictions = [x for x in (db.data.get_base_restriction_name(), db.data.get_search_restriction_name()) if x]
     restrictions = " :: ".join(restrictions)
     font = QFont()
     if restrictions:
         restrictions = " :: " + restrictions
         font.setBold(True)
         font.setItalic(True)
     self.virtual_library.setFont(font)
     title = u"{0} - || {1}{2} ||".format(__appname__, self.iactions["Choose Library"].library_name(), restrictions)
     self.setWindowTitle(title)
Example #33
0
 def set_favorite(self):
     item = self.dictionaries.currentItem()
     bf = QFont(self.dictionaries.font())
     bf.setItalic(True)
     for x in (item.parent().child(i) for i in xrange(item.parent().childCount())):
         x.setData(0, Qt.FontRole, bf if x is item else None)
     cc = unicode(item.parent().data(0, Qt.UserRole).toPyObject())
     lc = unicode(item.parent().parent().data(0, Qt.UserRole).toPyObject())
     d = item.data(0, Qt.UserRole).toPyObject()
     locale = '%s-%s' % (lc, cc)
     pl = dprefs['preferred_dictionaries']
     pl[locale] = d.id
     dprefs['preferred_dictionaries'] = pl
Example #34
0
class HeaderView(QHeaderView):  # {{{

    def __init__(self, *args):
        QHeaderView.__init__(self, *args)
        self.hover = -1
        self.current_font = QFont(self.font())
        self.current_font.setBold(True)
        self.current_font.setItalic(True)

    def event(self, e):
        if e.type() in (e.HoverMove, e.HoverEnter):
            self.hover = self.logicalIndexAt(e.pos())
        elif e.type() in (e.Leave, e.HoverLeave):
            self.hover = -1
        return QHeaderView.event(self, e)

    def paintSection(self, painter, rect, logical_index):
        opt = QStyleOptionHeader()
        self.initStyleOption(opt)
        opt.rect = rect
        opt.section = logical_index
        opt.orientation = self.orientation()
        opt.textAlignment = Qt.AlignHCenter | Qt.AlignVCenter
        model = self.parent().model()
        opt.text = model.headerData(logical_index, opt.orientation, Qt.DisplayRole).toString()
        if self.isSortIndicatorShown() and self.sortIndicatorSection() == logical_index:
            opt.sortIndicator = QStyleOptionHeader.SortDown if self.sortIndicatorOrder() == Qt.AscendingOrder else QStyleOptionHeader.SortUp
        opt.text = opt.fontMetrics.elidedText(opt.text, Qt.ElideRight, rect.width() - 4)
        if self.isEnabled():
            opt.state |= QStyle.State_Enabled
            if self.window().isActiveWindow():
                opt.state |= QStyle.State_Active
                if self.hover == logical_index:
                    opt.state |= QStyle.State_MouseOver
        sm = self.selectionModel()
        if opt.orientation == Qt.Vertical:
            try:
                opt.icon = model.headerData(logical_index, opt.orientation, Qt.DecorationRole)
                opt.iconAlignment = Qt.AlignVCenter
            except TypeError:
                pass
            if sm.isRowSelected(logical_index, QModelIndex()):
                opt.state |= QStyle.State_Sunken

        painter.save()
        if (
                (opt.orientation == Qt.Horizontal and sm.currentIndex().column() == logical_index) or
                (opt.orientation == Qt.Vertical and sm.currentIndex().row() == logical_index)):
            painter.setFont(self.current_font)
        self.style().drawControl(QStyle.CE_Header, opt, painter, self)
        painter.restore()
Example #35
0
 def data(self, index, role):
     try:
         widget = self.widgets[index.row()]
     except:
         return NONE
     if role == Qt.DisplayRole:
         return QVariant(widget.config_title())
     if role == Qt.DecorationRole:
         return QVariant(widget.config_icon())
     if role == Qt.FontRole:
         f = QFont()
         f.setBold(True)
         return QVariant(f)
     return NONE
Example #36
0
    def setBold(self, isBold=True):
        """
        Sets or unsets font of all labels in this widget to bold
        @param isBold: If true, sets the font of all labels in the widget to 
                       bold. 
        @type  isBold: bool
        @see:  B{MovePropertyManager.updateRotationDeltaLabels} for an example 
               on how this function is used. 
        """

        for label in self.labels:
            font = QFont(label.font())
            font.setBold(isBold)
            label.setFont(font)
Example #37
0
    def __init__(self,
                 gui,
                 msg,
                 size=100,
                 window_title='Marvin XD',
                 show_cancel=False,
                 on_top=False):
        flags = Qt.FramelessWindowHint
        if on_top:
            flags = Qt.FramelessWindowHint | Qt.WindowStaysOnTopHint
        QDialog.__init__(self, gui, flags)

        self._layout = QVBoxLayout()
        self.setLayout(self._layout)
        self.cancel_status = 0
        self.is_running = False

        # Add the spinner
        self.pi = ProgressIndicator(self)
        self.pi.setDisplaySize(size)
        self._layout.addSpacing(15)
        self._layout.addWidget(self.pi, 0, Qt.AlignHCenter)
        self._layout.addSpacing(15)

        # Fiddle with the message
        self.msg = QLabel(msg)
        #self.msg.setWordWrap(True)
        self.font = QFont()
        self.font.setPointSize(self.font.pointSize() + 2)
        self.msg.setFont(self.font)
        self._layout.addWidget(self.msg, 0, Qt.AlignHCenter)
        sp = QSizePolicy()
        sp.setHorizontalStretch(True)
        sp.setVerticalStretch(False)
        sp.setHeightForWidth(False)
        self.msg.setSizePolicy(sp)
        self.msg.setMinimumHeight(self.font.pointSize() + 8)

        self._layout.addSpacing(15)

        if show_cancel:
            self.bb = QDialogButtonBox()
            self.cancel_button = QPushButton(QIcon(I('window-close.png')),
                                             'Cancel')
            self.bb.addButton(self.cancel_button, self.bb.RejectRole)
            self.bb.clicked.connect(self.button_handler)
            self._layout.addWidget(self.bb)

        self.setWindowTitle(window_title)
        self.resize(self.sizeHint())
Example #38
0
 def setBold(self, isBold = True):
     """
     Sets or unsets font of all labels in this widget to bold
     @param isBold: If true, sets the font of all labels in the widget to 
                    bold. 
     @type  isBold: bool
     @see:  B{MovePropertyManager.updateRotationDeltaLabels} for an example 
            on how this function is used. 
     """
     
     for label in self.labels:          
         font = QFont(label.font())
         font.setBold(isBold)
         label.setFont(font)
Example #39
0
 def __init__(self, parent=None):
     QStatusBar.__init__(self, parent)
     self.default_message = __appname__ + ' ' + _('version') + ' ' + \
             self.get_version() + ' ' + _('created by Kovid Goyal')
     self.device_string = ''
     self.update_label = UpdateLabel('')
     self.addPermanentWidget(self.update_label)
     self.update_label.setVisible(False)
     self._font = QFont()
     self._font.setBold(True)
     self.setFont(self._font)
     self.defmsg = QLabel(self.default_message)
     self.defmsg.setFont(self._font)
     self.addWidget(self.defmsg)
Example #40
0
 def data(self, index, role):
     try:
         widget = self.widgets[index.row()]
     except:
         return NONE
     if role == Qt.DisplayRole:
         return QVariant(widget.config_title())
     if role == Qt.DecorationRole:
         return QVariant(widget.config_icon())
     if role == Qt.FontRole:
         f = QFont()
         f.setBold(True)
         return QVariant(f)
     return NONE
Example #41
0
    def popup(self, select_first=True):
        if self.disable_popup:
            return
        p = self
        m = p.model()
        widget = self.completer_widget()
        if widget is None:
            return
        screen = QApplication.desktop().availableGeometry(widget)
        h = (p.sizeHintForRow(0) * min(self.max_visible_items, m.rowCount()) +
             3) + 3
        hsb = p.horizontalScrollBar()
        if hsb and hsb.isVisible():
            h += hsb.sizeHint().height()

        rh = widget.height()
        pos = widget.mapToGlobal(QPoint(0, widget.height() - 2))
        w = min(widget.width(), screen.width())

        if (pos.x() + w) > (screen.x() + screen.width()):
            pos.setX(screen.x() + screen.width() - w)
        if pos.x() < screen.x():
            pos.setX(screen.x())

        top = pos.y() - rh - screen.top() + 2
        bottom = screen.bottom() - pos.y()
        h = max(h, p.minimumHeight())
        if h > bottom:
            h = min(max(top, bottom), h)

            if top > bottom:
                pos.setY(pos.y() - h - rh + 2)

        p.setGeometry(pos.x(), pos.y(), w, h)

        if (tweaks['preselect_first_completion'] and select_first
                and not self.currentIndex().isValid()
                and self.model().rowCount() > 0):
            self.setCurrentIndex(self.model().index(0))

        if not p.isVisible():
            if isosx and get_osx_version() >= (10, 9, 0):
                # On mavericks the popup menu seems to use a font smaller than
                # the widgets font, see for example:
                # https://bugs.launchpad.net/bugs/1243761
                fp = QFontInfo(widget.font())
                f = QFont()
                f.setPixelSize(fp.pixelSize())
                self.setFont(f)
            p.show()
Example #42
0
 def load_options(self, opts):
     self.opt_remember_window_size.setChecked(opts.remember_window_size)
     self.opt_remember_current_page.setChecked(opts.remember_current_page)
     self.opt_wheel_flips_pages.setChecked(opts.wheel_flips_pages)
     self.opt_page_flip_duration.setValue(opts.page_flip_duration)
     fms = opts.font_magnification_step
     if fms < 0.01 or fms > 1:
         fms = 0.2
     self.opt_font_mag_step.setValue(int(fms * 100))
     self.opt_line_scrolling_stops_on_pagebreaks.setChecked(
         opts.line_scrolling_stops_on_pagebreaks)
     self.serif_family.setCurrentFont(QFont(opts.serif_family))
     self.sans_family.setCurrentFont(QFont(opts.sans_family))
     self.mono_family.setCurrentFont(QFont(opts.mono_family))
     self.default_font_size.setValue(opts.default_font_size)
     self.minimum_font_size.setValue(opts.minimum_font_size)
     self.mono_font_size.setValue(opts.mono_font_size)
     self.standard_font.setCurrentIndex({
         'serif': 0,
         'sans': 1,
         'mono': 2
     }[opts.standard_font])
     self.css.setPlainText(opts.user_css)
     self.max_fs_width.setValue(opts.max_fs_width)
     self.max_fs_height.setValue(opts.max_fs_height)
     pats, names = self.hyphenate_pats, self.hyphenate_names
     try:
         idx = pats.index(opts.hyphenate_default_lang)
     except ValueError:
         idx = pats.index('en_us')
     idx = self.hyphenate_default_lang.findText(names[idx])
     self.hyphenate_default_lang.setCurrentIndex(idx)
     self.hyphenate.setChecked(opts.hyphenate)
     self.hyphenate_default_lang.setEnabled(opts.hyphenate)
     self.opt_fit_images.setChecked(opts.fit_images)
     self.opt_fullscreen_clock.setChecked(opts.fullscreen_clock)
     self.opt_fullscreen_scrollbar.setChecked(opts.fullscreen_scrollbar)
     self.opt_start_in_fullscreen.setChecked(opts.start_in_fullscreen)
     self.opt_show_fullscreen_help.setChecked(opts.show_fullscreen_help)
     self.opt_fullscreen_pos.setChecked(opts.fullscreen_pos)
     self.opt_cols_per_screen.setValue(opts.cols_per_screen)
     self.opt_override_book_margins.setChecked(not opts.use_book_margins)
     for x in ('top', 'bottom', 'side'):
         getattr(self,
                 'opt_%s_margin' % x).setValue(getattr(opts, x + '_margin'))
     for x in ('text', 'background'):
         setattr(self, 'current_%s_color' % x,
                 getattr(opts, '%s_color' % x))
     self.update_sample_colors()
     self.opt_show_controls.setChecked(opts.show_controls)
Example #43
0
class StatusBar(QStatusBar): # {{{

    def __init__(self, parent=None):
        QStatusBar.__init__(self, parent)
        self.default_message = __appname__ + ' ' + _('version') + ' ' + \
                __version__ + ' ' + _('created by Kovid Goyal')
        self.device_string = ''
        self._font = QFont()
        self._font.setBold(True)
        self.setFont(self._font)

        self.w = QLabel(self.default_message)
        self.w.setFont(self._font)
        self.addWidget(self.w)
Example #44
0
    def popup(self, select_first=True):
        if self.disable_popup:
            return
        p = self
        m = p.model()
        widget = self.completer_widget()
        if widget is None:
            return
        screen = QApplication.desktop().availableGeometry(widget)
        h = (p.sizeHintForRow(0) * min(self.max_visible_items, m.rowCount()) +
                3) + 3
        hsb = p.horizontalScrollBar()
        if hsb and hsb.isVisible():
            h += hsb.sizeHint().height()

        rh = widget.height()
        pos = widget.mapToGlobal(QPoint(0, widget.height() - 2))
        w = min(widget.width(), screen.width())

        if (pos.x() + w) > (screen.x() + screen.width()):
            pos.setX(screen.x() + screen.width() - w)
        if pos.x() < screen.x():
            pos.setX(screen.x())

        top = pos.y() - rh - screen.top() + 2
        bottom = screen.bottom() - pos.y()
        h = max(h, p.minimumHeight())
        if h > bottom:
            h = min(max(top, bottom), h)

            if top > bottom:
                pos.setY(pos.y() - h - rh + 2)

        p.setGeometry(pos.x(), pos.y(), w, h)

        if (tweaks['preselect_first_completion'] and select_first and not
                self.currentIndex().isValid() and self.model().rowCount() > 0):
            self.setCurrentIndex(self.model().index(0))

        if not p.isVisible():
            if isosx and get_osx_version() >= (10, 9, 0):
                # On mavericks the popup menu seems to use a font smaller than
                # the widgets font, see for example:
                # https://bugs.launchpad.net/bugs/1243761
                fp = QFontInfo(widget.font())
                f = QFont()
                f.setPixelSize(fp.pixelSize())
                self.setFont(f)
            p.show()
Example #45
0
File: toc.py Project: Eksmo/calibre
 def __init__(self, spine, toc, depth, all_items, parent=None):
     text = toc.text
     if text:
         text = re.sub(r'\s', ' ', text)
     self.title = text
     self.parent = parent
     QStandardItem.__init__(self, text if text else '')
     self.abspath = toc.abspath
     self.fragment = toc.fragment
     all_items.append(self)
     self.bold_font = QFont(self.font())
     self.bold_font.setBold(True)
     self.normal_font = self.font()
     for t in toc:
         self.appendRow(TOCItem(spine, t, depth+1, all_items, parent=self))
     self.setFlags(Qt.ItemIsEnabled)
     spos = 0
     for i, si in enumerate(spine):
         if si == self.abspath:
             spos = i
             break
     try:
         am = getattr(spine[i], 'anchor_map', {})
     except UnboundLocalError:
         # Spine was empty?
         am = {}
     frag = self.fragment if (self.fragment and self.fragment in am) else None
     self.starts_at = spos
     self.start_anchor = frag
     self.start_src_offset = am.get(frag, 0)
     self.depth = depth
     self.is_being_viewed = False
    def draw_glpane_label_text(self, text):
        """
        Draw a text label for the glpane as a whole.
        
        @note: called indirectly from GLPane.paintGL shortly after
               it calls _do_graphicsMode_Draw(), via GraphicsMode.draw_glpane_label
        """
        #bruce 090219 moved this here from part of Part.draw_text_label
        # (after a temporary stop in the short-lived class PartDrawer);
        # the other part is now our caller GraphicsMode.draw_glpane_label.

        # (note: caller catches exceptions, so we don't have to bother)
        
        glDisable(GL_LIGHTING)
        glDisable(GL_DEPTH_TEST)
            # Note: disabling GL_DEPTH_TEST properly affects 2d renderText
            # (as used here), but not 3d renderText. For more info see
            # today's comments in Guides.py. [bruce 081204 comment]
        glPushMatrix() # REVIEW: needed? [bruce 081204 question]
        font = QFont(QString("Helvetica"), 24, QFont.Bold)
        self.qglColor(Qt.red) # this needs to be impossible to miss -- not nice-looking!
            #e tho it might be better to pick one of several bright colors
            # by hashing the partname, so as to change the color when the part changes.
        # this version of renderText uses window coords (0,0 at upper left)
        # rather than model coords (but I'm not sure what point on the string-image
        # we're setting the location of here -- guessing it's bottom-left corner):
        self.renderText(25,40, QString(text), font)
        glPopMatrix()
        glEnable(GL_DEPTH_TEST)
        glEnable(GL_LIGHTING)
        return
Example #47
0
 def apply_theme(self, theme):
     self.theme = theme
     pal = self.palette()
     pal.setColor(pal.Base, theme_color(theme, 'Normal', 'bg'))
     pal.setColor(pal.AlternateBase, theme_color(theme, 'CursorLine', 'bg'))
     pal.setColor(pal.Text, theme_color(theme, 'Normal', 'fg'))
     pal.setColor(pal.Highlight, theme_color(theme, 'Visual', 'bg'))
     pal.setColor(pal.HighlightedText, theme_color(theme, 'Visual', 'fg'))
     self.setPalette(pal)
     self.tooltip_palette = pal = QPalette()
     pal.setColor(pal.ToolTipBase, theme_color(theme, 'Tooltip', 'bg'))
     pal.setColor(pal.ToolTipText, theme_color(theme, 'Tooltip', 'fg'))
     self.line_number_palette = pal = QPalette()
     pal.setColor(pal.Base, theme_color(theme, 'LineNr', 'bg'))
     pal.setColor(pal.Text, theme_color(theme, 'LineNr', 'fg'))
     pal.setColor(pal.BrightText, theme_color(theme, 'LineNrC', 'fg'))
     self.match_paren_format = theme_format(theme, 'MatchParen')
     font = self.font()
     ff = tprefs['editor_font_family']
     if ff is None:
         ff = default_font_family()
     font.setFamily(ff)
     font.setPointSize(tprefs['editor_font_size'])
     self.tooltip_font = QFont(font)
     self.tooltip_font.setPointSize(font.pointSize() - 1)
     self.setFont(font)
     self.highlighter.apply_theme(theme)
     w = self.fontMetrics()
     self.number_width = max(map(lambda x:w.width(str(x)), xrange(10)))
     self.size_hint = QSize(100 * w.averageCharWidth(), 50 * w.height())
     self.highlight_color = theme_color(theme, 'HighlightRegion', 'bg')
     self.highlight_cursor_line()
Example #48
0
    def __init__(self, msg, args, db, ids, cc_widgets, s_r_func,
                 parent=None, window_title=_('Working')):
        QDialog.__init__(self, parent)

        self._layout = QVBoxLayout()
        self.setLayout(self._layout)
        self.msg_text = msg
        self.msg = QLabel(msg+'        ') # Ensure dialog is wide enough
        #self.msg.setWordWrap(True)
        self.font = QFont()
        self.font.setPointSize(self.font.pointSize() + 8)
        self.msg.setFont(self.font)
        self.pi = ProgressIndicator(self)
        self.pi.setDisplaySize(100)
        self._layout.addWidget(self.pi, 0, Qt.AlignHCenter)
        self._layout.addSpacing(15)
        self._layout.addWidget(self.msg, 0, Qt.AlignHCenter)
        self.setWindowTitle(window_title)
        self.resize(self.sizeHint())
        self.start()

        self.args = args
        self.series_start_value = None
        self.db = db
        self.ids = ids
        self.error = None
        self.cc_widgets = cc_widgets
        self.s_r_func = s_r_func
        self.do_one_signal.connect(self.do_one_safe, Qt.QueuedConnection)
Example #49
0
    def __init__(self, parent = None):
        '''
        Constructor
        '''
        super(VoivoiShow, self).__init__(parent)
        #self.setStyleSheet("background: #000;")
        
        self.splashscreen = QImage("res/splashscreen.jpg")
        #print(self.splashscreen.isNull())
        if not self.splashscreen.isNull():
            self.imgList.append(self.splashscreen)
                                      
        self.imageLabel = QLabel()
        self.imageLabel.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Ignored)
        self.imageLabel.setParent(self)

        self.httpPool = urllib3.PoolManager()
        
        self.slideIterator = 0
        self.timer.timeout.connect(self.nextImage)
        self.updateTimer = QTimer()
        self.updateTimer.timeout.connect(self.updateImages)
        self.mostRecent = datetime.fromtimestamp(0)
        
        self.layout = QHBoxLayout()
        self.layout.setMargin(0)
        self.layout.addWidget(self.imageLabel)
        self.layout.setAlignment(self.imageLabel, Qt.AlignHCenter)
        self.setLayout(self.layout)
        self.voivoifont = QFont("Helvetica", 48)
        self.voivoifont.setBold(True)
Example #50
0
 def set_value(self, g, val):
     from calibre.gui2.convert.xpath_wizard import XPathEdit
     from calibre.gui2.convert.regex_builder import RegexEdit
     from calibre.gui2.widgets import EncodingComboBox
     if self.set_value_handler(g, val):
         return
     if isinstance(g, (QSpinBox, QDoubleSpinBox)):
         g.setValue(val)
     elif isinstance(g, (QLineEdit, QTextEdit)):
         if not val: val = ''
         getattr(g, 'setPlainText', g.setText)(val)
         getattr(g, 'setCursorPosition', lambda x: x)(0)
     elif isinstance(g, QFontComboBox):
         g.setCurrentFont(QFont(val or ''))
     elif isinstance(g, FontFamilyChooser):
         g.font_family = val
     elif isinstance(g, EncodingComboBox):
         if val:
             g.setEditText(val)
         else:
             g.setCurrentIndex(0)
     elif isinstance(g, QComboBox) and val:
         idx = g.findText(val, Qt.MatchFixedString)
         if idx < 0:
             g.addItem(val)
             idx = g.findText(val, Qt.MatchFixedString)
         g.setCurrentIndex(idx)
     elif isinstance(g, QCheckBox):
         g.setCheckState(Qt.Checked if bool(val) else Qt.Unchecked)
     elif isinstance(g, (XPathEdit, RegexEdit)):
         g.edit.setText(val if val else '')
     else:
         raise Exception('Can\'t set value %s in %s'%(repr(val),
             unicode(g.objectName())))
     self.post_set_value(g, val)
Example #51
0
class StatusBar(QStatusBar): # {{{

    def __init__(self, parent=None):
        QStatusBar.__init__(self, parent)
        self.default_message = __appname__ + ' ' + _('version') + ' ' + \
                self.get_version() + ' ' + _('created by Kovid Goyal')
        self.device_string = ''
        self.update_label = UpdateLabel('')
        self.addPermanentWidget(self.update_label)
        self.update_label.setVisible(False)
        self._font = QFont()
        self._font.setBold(True)
        self.setFont(self._font)
        self.defmsg = QLabel(self.default_message)
        self.defmsg.setFont(self._font)
        self.addWidget(self.defmsg)

    def initialize(self, systray=None):
        self.systray = systray
        self.notifier = get_notifier(systray)

    def device_connected(self, devname):
        self.device_string = _('Connected ') + devname
        self.defmsg.setText(self.default_message + ' ..::.. ' +
                self.device_string)
        self.clearMessage()

    def device_disconnected(self):
        self.device_string = ''
        self.defmsg.setText(self.default_message)
        self.clearMessage()

    def get_version(self):
        return get_version()

    def show_message(self, msg, timeout=0):
        self.showMessage(msg, timeout)
        if self.notifier is not None and not config['disable_tray_notification']:
            if isosx and isinstance(msg, unicode):
                try:
                    msg = msg.encode(preferred_encoding)
                except UnicodeEncodeError:
                    msg = msg.encode('utf-8')
            self.notifier(msg)

    def clear_message(self):
        self.clearMessage()
Example #52
0
 def __init__(self, *args, **kwargs):
     QStyledItemDelegate.__init__(self, *args, **kwargs)
     self.rf = QFont(rating_font())
     self.em = Qt.ElideMiddle
     delta = 0
     if iswindows and sys.getwindowsversion().major >= 6:
         delta = 2
     self.rf.setPointSize(QFontInfo(QApplication.font()).pointSize()+delta)
 def __init__(self, parent, icon_name, title):
     QHBoxLayout.__init__(self)
     title_font = QFont()
     title_font.setPointSize(16)
     title_image_label = QLabel(parent)
     pixmap = get_pixmap(icon_name)
     if pixmap is None:
         error_dialog(parent, _('Restart required'),
                      _('You must restart Calibre before using this plugin!'), show=True)
     else:
         title_image_label.setPixmap(pixmap)
     title_image_label.setMaximumSize(32, 32)
     title_image_label.setScaledContents(True)
     self.addWidget(title_image_label)
     shelf_label = QLabel(title, parent)
     shelf_label.setFont(title_font)
     self.addWidget(shelf_label)
     self.insertStretch(-1)
Example #54
0
    def do_paint(self, painter, option, index):
        text = unicode(index.data(Qt.DisplayRole).toString())
        font = QFont(option.font)
        font.setPointSize(QFontInfo(font).pointSize() * 1.5)
        font2 = QFont(font)
        font2.setFamily(text)

        system, has_latin = writing_system_for_font(font2)
        if has_latin:
            font = font2

        r = option.rect

        if option.state & QStyle.State_Selected:
            painter.setPen(QPen(option.palette.highlightedText(), 0))

        if (option.direction == Qt.RightToLeft):
            r.setRight(r.right() - 4)
        else:
            r.setLeft(r.left() + 4)

        painter.setFont(font)
        painter.drawText(r, Qt.AlignVCenter|Qt.AlignLeading|Qt.TextSingleLine, text)

        if (system != QFontDatabase.Any):
            w = painter.fontMetrics().width(text + "  ")
            painter.setFont(font2)
            sample = QFontDatabase().writingSystemSample(system)
            if (option.direction == Qt.RightToLeft):
                r.setRight(r.right() - w)
            else:
                r.setLeft(r.left() + w)
            painter.drawText(r, Qt.AlignVCenter|Qt.AlignLeading|Qt.TextSingleLine, sample)
Example #55
0
    def process_duplicates(self, db, duplicates):
        ta = _('%(title)s by %(author)s')
        bf = QFont(self.dup_list.font())
        bf.setBold(True)
        itf = QFont(self.dup_list.font())
        itf.setItalic(True)

        for mi, cover, formats in duplicates:
            item = QTreeWidgetItem([ta%dict(
                title=mi.title, author=mi.format_field('authors')[1])] , 0)
            item.setCheckState(0, Qt.Checked)
            item.setFlags(Qt.ItemIsEnabled|Qt.ItemIsUserCheckable)
            item.setData(0, Qt.FontRole, bf)
            item.setData(0, Qt.UserRole, (mi, cover, formats))
            matching_books = db.books_with_same_title(mi)

            def add_child(text):
                c = QTreeWidgetItem([text], 1)
                c.setFlags(Qt.ItemIsEnabled)
                item.addChild(c)
                return c

            add_child(_('Already in calibre:')).setData(0, Qt.FontRole, itf)

            for book_id in matching_books:
                aut = [a.replace('|', ',') for a in (db.authors(book_id,
                    index_is_id=True) or '').split(',')]
                add_child(ta%dict(
                    title=db.title(book_id, index_is_id=True),
                    author=authors_to_string(aut)))
            add_child('')

            yield item
Example #56
0
 def _getHeaderFont(self):
     """
     Returns the font used for the header.
     
     @return: the header font
     @rtype:  QFont
     """
     font = QFont()
     font.setFamily(PM_HEADER_FONT)
     font.setPointSize(PM_HEADER_FONT_POINT_SIZE)
     font.setBold(PM_HEADER_FONT_BOLD)
     return font