Пример #1
1
def entry_to_icon_text(entry, only_text=False):
    if only_text:
        return entry.get('name', entry.get('Name')) or _('Unknown')
    data = entry.get('icon_data')
    if data is None:
        icon = QIcon(I('blank.png'))
    else:
        pmap = QPixmap()
        pmap.loadFromData(bytes(data))
        icon = QIcon(pmap)
    return icon, entry.get('name', entry.get('Name')) or _('Unknown')
Пример #2
0
    def dump(self, items, out_stream, pdf_metadata):
        opts = self.opts
        page_size = get_page_size(self.opts)
        ml, mr = opts.margin_left, opts.margin_right
        self.doc = PdfDevice(
            out_stream, page_size=page_size, left_margin=ml,
            top_margin=opts.margin_top, right_margin=mr,
            bottom_margin=opts.margin_bottom,
            errors=self.log.error, debug=self.log.debug, compress=not
            opts.uncompressed_pdf, opts=opts, mark_links=opts.pdf_mark_links)
        self.painter = QPainter(self.doc)
        self.doc.set_metadata(title=pdf_metadata.title,
                              author=pdf_metadata.author,
                              tags=pdf_metadata.tags, mi=pdf_metadata.mi)
        self.doc_title = pdf_metadata.title
        self.doc_author = pdf_metadata.author

        for imgpath in items:
            self.log.debug('Processing %s...' % imgpath)
            self.doc.init_page()
            p = QPixmap()
            with lopen(imgpath, 'rb') as f:
                if not p.loadFromData(f.read()):
                    raise ValueError('Could not read image from: {}'.format(imgpath))
            draw_image_page(QRect(*self.doc.full_page_rect),
                    self.painter, p,
                    preserve_aspect_ratio=True)
            self.doc.end_page()
        if self.toc is not None and len(self.toc) > 0:
            self.doc.add_outline(self.toc)

        self.painter.end()

        if self.doc.errors_occurred:
            raise Exception('PDF Output failed, see log for details')
Пример #3
0
 def select_cover(self):
     files = choose_images(self, 'change cover dialog',
                          _('Choose cover for ') + unicode(self.title.text()))
     if not files:
         return
     _file = files[0]
     if _file:
         _file = os.path.abspath(_file)
         if not os.access(_file, os.R_OK):
             d = error_dialog(self.parent(), _('Cannot read'),
                     _('You do not have permission to read the file: ') + _file)
             d.exec_()
             return
         cf, cover = None, None
         try:
             cf = open(_file, "rb")
             cover = cf.read()
         except IOError as e:
             d = error_dialog(self.parent(), _('Error reading file'),
                     _("<p>There was an error reading from file: <br /><b>") + _file + "</b></p><br />"+str(e))
             d.exec_()
         if cover:
             pix = QPixmap()
             pix.loadFromData(cover)
             if pix.isNull():
                 d = error_dialog(self.parent(), _('Error reading file'),
                                   _file + _(" is not a valid picture"))
                 d.exec_()
             else:
                 self.cover_path.setText(_file)
                 self.set_cover_tooltip(pix)
                 self.cover.setPixmap(pix)
                 self.cover_changed = True
                 self.cpixmap = pix
                 self.cover_data = cover
Пример #4
0
    def __init__(self, controller):
        super().__init__()

        self.setWindowTitle("QuickText")
        self.setGeometry(100,100,1030,800)
        pixmap = QPixmap()
        pixmap.loadFromData(get_data(__name__, 'icon.png'))
        self.setWindowIcon(QIcon(pixmap))
        self.setStatusBar(QuiStatusBar())
        self.addDockWidget(Qt.RightDockWidgetArea, QuiDock(controller))

        self.setCentralWidget(controller.document_editor)
        self.addToolBar(QuiToolbar(self, 'FileToolbar', [
            (None, "Open", "Open a file", None, controller.load),
            (None, "Save", "Save the current file", None, controller.save),
            (None, "Exit", "Exit", None, controller.end),
        ]))

        self.addToolBar(QuiToolbar(self, 'FormatToolbar', [
            (None, "Heading 1", "Heading level one", "Ctrl+1", lambda: controller.document_editor.setCurrentFont(controller.document_editor.format_h1)),
            (None, "Heading 2", "Heading level two", "Ctrl+2", lambda: controller.document_editor.setCurrentFont(controller.document_editor.format_h2)),
            (None, "Heading 3", "Heading level three", "Ctrl+3", lambda: controller.document_editor.setCurrentFont(controller.document_editor.format_h3)),
            (None, "Heading 4", "Heading level four", "Ctrl+4", lambda: controller.document_editor.setCurrentFont(controller.document_editor.format_h4)),
            (None, "Heading 5", "Heading level five", "Ctrl+5", lambda: controller.document_editor.setCurrentFont(controller.document_editor.format_h5)),
            (None, "Heading 6", "Heading level six", "Ctrl+6", lambda: controller.document_editor.setCurrentFont(controller.document_editor.format_h6)),
            (None, "Body", "Simple body text", "Ctrl+`", lambda: controller.document_editor.setCurrentFont(controller.document_editor.format_p)),
        ]))
Пример #5
0
class CoverView(QWidget):
    def __init__(self, parent=None):
        QWidget.__init__(self, parent)
        self.current_pixmap_size = QSize(0, 0)
        self.pixmap = QPixmap()
        self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)

    def set_pixmap(self, data):
        self.pixmap.loadFromData(data)
        self.current_pixmap_size = self.pixmap.size()
        self.update()

    def paintEvent(self, event):
        if self.pixmap.isNull():
            return
        canvas_size = self.rect()
        width = self.current_pixmap_size.width()
        extrax = canvas_size.width() - width
        if extrax < 0:
            extrax = 0
        x = int(extrax / 2.0)
        height = self.current_pixmap_size.height()
        extray = canvas_size.height() - height
        if extray < 0:
            extray = 0
        y = int(extray / 2.0)
        target = QRect(x, y, min(canvas_size.width(), width), min(canvas_size.height(), height))
        p = QPainter(self)
        p.setRenderHints(QPainter.Antialiasing | QPainter.SmoothPixmapTransform)
        p.drawPixmap(target, self.pixmap.scaled(target.size(), Qt.KeepAspectRatio, Qt.SmoothTransformation))
        p.end()

    def sizeHint(self):
        return QSize(300, 400)
Пример #6
0
 def toggleCursor(self):
     if self.cursor().shape() == QCursor(Qt.ArrowCursor).shape():
         raw = QPixmap(":/gui/pics/pardusman-icon.png")
         raw.setMask(raw.mask())
         self.setCursor(QCursor(raw, 2, 2))
     else:
         self.unsetCursor()
Пример #7
0
def get_icons(zfp, name_or_list_of_names):
    '''
    Load icons from the plugin zip file

    :param name_or_list_of_names: List of paths to resources in the zip file using / as
                separator, or a single path

    :return: A dictionary of the form ``{name : QIcon}``. Any names
                that were not found in the zip file will be null QIcons.
                If a single path is passed in the return value will
                be A QIcon.
    '''
    from PyQt5.Qt import QIcon, QPixmap
    names = name_or_list_of_names
    ans = get_resources(zfp, names)
    if isinstance(names, basestring):
        names = [names]
    if ans is None:
        ans = {}
    if isinstance(ans, basestring):
        ans = dict([(names[0], ans)])

    ians = {}
    for name in names:
        p = QPixmap()
        raw = ans.get(name, None)
        if raw:
            p.loadFromData(raw)
        ians[name] = QIcon(p)
    if len(names) == 1:
        ians = ians.pop(names[0])
    return ians
Пример #8
0
    def show_pages(self):
        if self.error is not None:
            error_dialog(self, _('Failed to render'),
                _('Could not render this PDF file'), show=True, det_msg=self.error)
            self.reject()
            return
        self.stack.stop()
        files = glob(os.path.join(self.current_tdir, '*.jpg')) + glob(os.path.join(self.current_tdir, '*.jpeg'))
        if not files and not self.covers.count():
            error_dialog(self, _('Failed to render'),
                _('This PDF has no pages'), show=True)
            self.reject()
            return

        try:
            dpr = self.devicePixelRatioF()
        except AttributeError:
            dpr = self.devicePixelRatio()

        for i, f in enumerate(sorted(files)):
            p = QPixmap(f).scaled(self.covers.iconSize()*dpr, aspectRatioMode=Qt.IgnoreAspectRatio, transformMode=Qt.SmoothTransformation)
            p.setDevicePixelRatio(dpr)
            i = QListWidgetItem(_('page %d') % (self.first + i))
            i.setData(Qt.DecorationRole, p)
            i.setData(Qt.UserRole, f)
            self.covers.addItem(i)
        self.first += len(files)
        if len(files) == PAGES_PER_RENDER:
            self.more_pages.setVisible(True)
Пример #9
0
class ColorButton(QToolButton):
    def __init__(self, color, parent=None):
        QToolButton.__init__(self, parent)
        self.setIconSize(QSize(50, 25))
        self.pix = QPixmap(self.iconSize())
        self._color = QColor('#' + color)
        self.pix.fill(self._color)
        self.setIcon(QIcon(self.pix))
        self.clicked.connect(self.choose_color)

    @dynamic_property
    def color(self):
        def fget(self):
            return self._color.name(QColor.HexRgb)[1:]

        def fset(self, val):
            self._color = QColor('#' + val)

        return property(fget=fget, fset=fset)

    def update_display(self):
        self.pix.fill(self._color)
        self.setIcon(QIcon(self.pix))

    def choose_color(self):
        c = QColorDialog.getColor(self._color, self, _('Choose color'))
        if c.isValid():
            self._color = c
            self.update_display()
Пример #10
0
    def initialize_metadata_options(self):
        self.initialize_combos()
        self.author.editTextChanged.connect(self.deduce_author_sort)

        mi = self.db.get_metadata(self.book_id, index_is_id=True)
        self.title.setText(mi.title)
        self.publisher.show_initial_value(mi.publisher if mi.publisher else '')
        self.author_sort.setText(mi.author_sort if mi.author_sort else '')
        self.tags.setText(', '.join(mi.tags if mi.tags else []))
        self.tags.update_items_cache(self.db.all_tags())
        self.comment.html = comments_to_html(mi.comments) if mi.comments else ''
        self.series.show_initial_value(mi.series if mi.series else '')
        if mi.series_index is not None:
            try:
                self.series_index.setValue(mi.series_index)
            except:
                self.series_index.setValue(1.0)

        cover = self.db.cover(self.book_id, index_is_id=True)
        if cover:
            pm = QPixmap()
            pm.loadFromData(cover)
            if not pm.isNull():
                self.cover.setPixmap(pm)
                self.cover_data = cover
                self.set_cover_tooltip(pm)
        else:
            self.cover.setPixmap(QPixmap(I('default_cover.png')))
            self.cover.setToolTip(_('This book has no cover'))
        for x in ('author', 'series', 'publisher'):
            x = getattr(self, x)
            x.lineEdit().deselect()
Пример #11
0
 def render_emblems(item, emblems):
     emblems = tuple(emblems)
     if not emblems:
         return
     icon = self.rendered_emblem_cache.get(emblems, None)
     if icon is None:
         pixmaps = []
         for emblem in emblems:
             pm = self.emblem_cache.get(emblem, None)
             if pm is None:
                 pm = self.emblem_cache[emblem] = QPixmap(
                     I(emblem)).scaled(self.iconSize(), transformMode=Qt.SmoothTransformation)
             pixmaps.append(pm)
         num = len(pixmaps)
         w, h = pixmaps[0].width(), pixmaps[0].height()
         if num == 1:
             icon = self.rendered_emblem_cache[emblems] = QIcon(pixmaps[0])
         else:
             canvas = QPixmap((num * w) + ((num-1)*2), h)
             canvas.fill(Qt.transparent)
             painter = QPainter(canvas)
             for i, pm in enumerate(pixmaps):
                 painter.drawPixmap(i * (w + 2), 0, pm)
             painter.end()
             icon = self.rendered_emblem_cache[emblems] = canvas
     item.setData(0, Qt.DecorationRole, icon)
Пример #12
0
    def show_pages(self):
        self.loading.setVisible(False)
        if self.error is not None:
            error_dialog(self, _('Failed to render'),
                _('Could not render this PDF file'), show=True)
            self.reject()
            return
        files = (glob(os.path.join(self.tdir, '*.jpg')) +
                 glob(os.path.join(self.tdir, '*.jpeg')))
        if not files:
            error_dialog(self, _('Failed to render'),
                _('This PDF has no pages'), show=True)
            self.reject()
            return

        try:
            dpr = self.devicePixelRatioF()
        except AttributeError:
            dpr = self.devicePixelRatio()

        for i, f in enumerate(sorted(files)):
            p = QPixmap(f).scaled(self.covers.iconSize()*dpr, aspectRatioMode=Qt.IgnoreAspectRatio, transformMode=Qt.SmoothTransformation)
            p.setDevicePixelRatio(dpr)
            i = QListWidgetItem(_('page %d') % (i + 1))
            i.setData(Qt.DecorationRole, p)
            i.setData(Qt.UserRole, f)
            self.covers.addItem(i)
Пример #13
0
    def __init__(self, parent):
        QWizard.__init__(self, parent)
        self.setWindowTitle(__appname__+' '+_('welcome wizard'))
        p  = QPixmap()
        p.loadFromData(open(P('content_server/calibre.png'), 'rb').read())
        self.setPixmap(self.LogoPixmap, p.scaledToHeight(80,
            Qt.SmoothTransformation))
        self.setPixmap(self.WatermarkPixmap,
            QPixmap(I('welcome_wizard.png')))
        self.setPixmap(self.BackgroundPixmap, QPixmap(I('wizard.png')))
        self.device_page = DevicePage()
        self.library_page = LibraryPage()
        self.library_page.retranslate.connect(self.retranslate)
        self.finish_page = FinishPage()
        self.set_finish_text()
        self.kindle_page = KindlePage()
        self.stanza_page = StanzaPage()
        self.setPage(self.library_page.ID, self.library_page)
        self.setPage(self.device_page.ID, self.device_page)
        self.setPage(self.finish_page.ID, self.finish_page)
        self.setPage(self.kindle_page.ID, self.kindle_page)
        self.setPage(self.stanza_page.ID, self.stanza_page)

        self.device_extra_page = None
        nh, nw = min_available_height()-75, available_width()-30
        if nh < 0:
            nh = 580
        if nw < 0:
            nw = 400
        nh = min(400, nh)
        nw = min(580, nw)
        self.resize(nw, nh)
        self.set_button_texts()
Пример #14
0
 def onSavePlotter(self):
     saveFile, exp = QFileDialog.getSaveFileName(self, '', '', self.tr('Рисунок (*.png *.jpg)'))
     if not saveFile:
         return
     pixmap = QPixmap(self._pixmapSaveWidth, self._pixmapSaveHeight)
     painter = QPainter(pixmap)
     self.drawOnPlotter(painter)
     pixmap.save(saveFile)
Пример #15
0
 def data(self, index, role):
     row, col = index.row(), index.column()
     if row >= len(self.matches):
         return None
     result = self.matches[row]
     if role == Qt.DisplayRole:
         if col == 1:
             t = result.title if result.title else _('Unknown')
             a = result.author if result.author else ''
             return ('<b>%s</b><br><i>%s</i>' % (t, a))
         elif col == 2:
             return (result.price)
         elif col == 4:
             return ('<span>%s<br>%s</span>' % (result.store_name, result.formats))
         return None
     elif role == Qt.DecorationRole:
         if col == 0 and result.cover_data:
             p = QPixmap()
             p.loadFromData(result.cover_data)
             p.setDevicePixelRatio(QApplication.instance().devicePixelRatio())
             return p
         if col == 3:
             if result.drm == SearchResult.DRM_LOCKED:
                 return (self.DRM_LOCKED_ICON)
             elif result.drm == SearchResult.DRM_UNLOCKED:
                 return (self.DRM_UNLOCKED_ICON)
             elif result.drm == SearchResult.DRM_UNKNOWN:
                 return (self.DRM_UNKNOWN_ICON)
         if col == 5:
             if result.downloads:
                 return (self.DOWNLOAD_ICON)
         if col == 6:
             if result.affiliate:
                 return (self.DONATE_ICON)
     elif role == Qt.ToolTipRole:
         if col == 1:
             return ('<p>%s</p>' % result.title)
         elif col == 2:
             return ('<p>' + _('Detected price as: %s. Check with the store before making a purchase to verify this price is correct. This price often does not include promotions the store may be running.') % result.price + '</p>')  # noqa
         elif col == 3:
             if result.drm == SearchResult.DRM_LOCKED:
                 return ('<p>' + _('This book as been detected as having DRM restrictions. This book may not work with your reader and you will have limitations placed upon you as to what you can do with this book. Check with the store before making any purchases to ensure you can actually read this book.') + '</p>')  # noqa
             elif result.drm == SearchResult.DRM_UNLOCKED:
                 return ('<p>' + _('This book has been detected as being DRM Free. You should be able to use this book on any device provided it is in a format calibre supports for conversion. However, before making a purchase double check the DRM status with the store. The store may not be disclosing the use of DRM.') + '</p>')  # noqa
             else:
                 return ('<p>' + _('The DRM status of this book could not be determined. There is a very high likelihood that this book is actually DRM restricted.') + '</p>')  # noqa
         elif col == 4:
             return ('<p>%s</p>' % result.formats)
         elif col == 5:
             if result.downloads:
                 return ('<p>' + _('The following formats can be downloaded directly: %s.') % ', '.join(result.downloads.keys()) + '</p>')
         elif col == 6:
             if result.affiliate:
                 return ('<p>' + _('Buying from this store supports the calibre developer: %s.') % result.plugin_author + '</p>')
     elif role == Qt.SizeHintRole:
         return QSize(64, 64)
     return None
Пример #16
0
 def entry_to_icon_text(entry):
     data = entry.get('icon_data')
     if data is None:
         icon = QIcon(I('blank.png'))
     else:
         pmap = QPixmap()
         pmap.loadFromData(bytes(data))
         icon = QIcon(pmap)
     return icon, entry['Name']
Пример #17
0
    def __init__(self, current_cover, parent=None):
        QAbstractListModel.__init__(self, parent)

        if current_cover is None:
            current_cover = QPixmap(I('default_cover.png'))
        current_cover.setDevicePixelRatio(QApplication.instance().devicePixelRatio())

        self.blank = QIcon(I('blank.png')).pixmap(*CoverDelegate.ICON_SIZE)
        self.cc = current_cover
        self.reset_covers(do_reset=False)
Пример #18
0
def get_pixmap(icon_name):
    '''
    Retrieve a QPixmap for the named image
    Any icons belonging to the plugin must be prefixed with 'images/'
    '''
    global plugin_icon_resources, plugin_name

    if not icon_name.startswith('images/'):
        # We know this is definitely not an icon belonging to this plugin
        pixmap = QPixmap()
        pixmap.load(I(icon_name))
        return pixmap

    # Check to see whether the icon exists as a Calibre resource
    # This will enable skinning if the user stores icons within a folder like:
    # ...\AppData\Roaming\calibre\resources\images\Plugin Name\
    if plugin_name:
        local_images_dir = get_local_images_dir(plugin_name)
        local_image_path = os.path.join(local_images_dir, icon_name.replace('images/', ''))
        if os.path.exists(local_image_path):
            pixmap = QPixmap()
            pixmap.load(local_image_path)
            return pixmap

    # As we did not find an icon elsewhere, look within our zip resources
    if icon_name in plugin_icon_resources:
        pixmap = QPixmap()
        pixmap.loadFromData(plugin_icon_resources[icon_name])
        return pixmap
    return None
Пример #19
0
def get_icon(name):
    if not name.startswith("images/"):
        name = "images/" + name
    try:
        return _icon_cache[name]
    except KeyError:
        raw = get_data_as_file(name).read()
        pixmap = QPixmap()
        pixmap.loadFromData(raw)
        icon = _icon_cache[name] = QIcon()
        icon.addPixmap(pixmap)
        return icon
Пример #20
0
 def __init__(self, parent, collection, item):
     QWidget.__init__(self, parent)
     self.setupUi(self)
     self.parent = parent
     self.item = item
     self.collection = collection
     self.header.setText(collection.title)
     self.description.setText(collection.description)
     icon = QPixmap(":/gui/pics/%s" % collection.icon)
     if icon.isNull():
         icon = QPixmap(":/gui/pics/systemsettings.png")
     self.icon.setPixmap(icon)
Пример #21
0
 def get_icon(self, icon_name):
     """
     Check to see whether the icon exists as a Calibre resource
     This will enable skinning if the user stores icons within a folder like:
     ...\AppData\Roaming\calibre\resources\images\Plugin Name\
     """
     icon_path = os.path.join(config_dir, 'resources', 'images', self.name, icon_name)
     if not os.path.exists(icon_path):
         return get_icons(self.plugin_path, 'images/{0}'.format(icon_name))
     pixmap = QPixmap()
     pixmap.load(icon_path)
     return QIcon(pixmap)
 def subscribe_to_field(self, component, field):
     
     if (component, field) in self._m3field_values:
         rospy.logwarn("Already subscribed to field. Exiting.")
         return
             
     try:
         resp = self.req_vals_client(component, field, "", self.hz_rate.value())
     except rospy.ServiceException:
         rospy.logerr("Could not call request_values")
         return
     
     print resp.values
     
     dt = Floats
     topic = str("/meka_ros_pub/"+component+"/"+field)
     self._dashboard_mekaros_subs[(component, field)] = rospy.Subscriber(topic, dt, self.field_callback, (component, field))
     self._m3field_values[(component, field)] = []
     
     name_label = QLabel(component+"->"+field+":")
     for val in resp.values:
         label = QLabel(str(val)[:5])
         label.setStyleSheet("border: 2px solid grey");
         self._m3field_values[(component, field)].append(label)
     
     idx = self.inspection_layout.rowCount()
     
     plot_pixmap = QPixmap(self._path + "/plot.png")
     plot_icon = QIcon(plot_pixmap);
     #plot_btn = QPushButton()
     #plot_btn.setIcon(plot_icon)
     #plot_btn.setIconSize(plot_pixmap.rect().size())
     #plot_btn.setFixedWidth(30)
     #plot_btn.clicked.connect(partial(self.plot_values, component, field))
     
     close_pixmap = QPixmap(self._path + "/close.png")
     close_icon = QIcon(close_pixmap);
     close_btn = QPushButton()
     close_btn.setIcon(close_icon)
     close_btn.setIconSize(close_pixmap.rect().size())
     close_btn.setFixedWidth(30)
     close_btn.clicked.connect(partial(self.remove_row, self.inspection_layout, idx, False, component, field))
     
     self.inspection_layout.addWidget(name_label, idx, 0)
     val_layout = QHBoxLayout()
     for label in self._m3field_values[(component, field)]:
         val_layout.addWidget(label);
     self.inspection_layout.addLayout(val_layout, idx, 1)
     #self.inspection_layout.addWidget(plot_btn, idx, 2)
     self.inspection_layout.addWidget(close_btn, idx, 3)
Пример #23
0
 def icon(self):
     if self._icon is None:
         self._icon = QIcon()
         url = places.favicon_url(self.place_id)
         if url is not None:
             f = QApplication.instance().disk_cache.data(QUrl(url))
             if f is not None:
                 with closing(f):
                     raw = f.readAll()
                 p = QPixmap()
                 p.loadFromData(raw)
                 if not p.isNull():
                     self._icon.addPixmap(p)
     return self._icon
Пример #24
0
 def update_brush(self):
     self.brush = QBrush(self.bcol)
     if self.btex:
         from calibre.gui2.preferences.texture_chooser import texture_path
         path = texture_path(self.btex)
         if path:
             p = QPixmap(path)
             try:
                 dpr = self.devicePixelRatioF()
             except AttributeError:
                 dpr = self.devicePixelRatio()
             p.setDevicePixelRatio(dpr)
             self.brush.setTexture(p)
     self.update()
Пример #25
0
 def __init__(self, data, encoding, x0, y0, x1, y1, xsize, ysize):
     p = QPixmap()
     p.loadFromData(data, encoding, Qt.AutoColor)
     w, h = p.width(), p.height()
     p = p.copy(x0, y0, min(w, x1-x0), min(h, y1-y0))
     if p.width() != xsize or p.height() != ysize:
         p = p.scaled(xsize, ysize, Qt.IgnoreAspectRatio, Qt.SmoothTransformation)
     QGraphicsPixmapItem.__init__(self, p)
     self.height, self.width = ysize, xsize
     self.setTransformationMode(Qt.SmoothTransformation)
     self.setShapeMode(QGraphicsPixmapItem.BoundingRectShape)
Пример #26
0
 def update_cover(self, pmap=None, cdata=None):
     if pmap is None:
         pmap = QPixmap()
         pmap.loadFromData(cdata)
     if pmap.isNull():
         return
     self.pixmap = pmap
     self.do_layout()
     self.update()
     self.update_tooltip(getattr(self.parent(), 'current_path', ''))
     if not config['disable_animations']:
         self.animation.start()
     id_ = self.data.get('id', None)
     if id_ is not None:
         self.cover_changed.emit(id_, cdata or pixmap_to_data(pmap))
Пример #27
0
def read_icon(handle, icon):
    must_use_qt()
    resource = win32api.LoadResource(handle, win32con.RT_ICON, icon.id)
    pixmap = QPixmap()
    pixmap.loadFromData(resource)
    hicon = None
    if pixmap.isNull():
        if icon.width > 0 and icon.height > 0:
            hicon = ctypes.windll.user32.CreateIconFromResourceEx(
                resource, len(resource), True, 0x00030000, icon.width, icon.height, win32con.LR_DEFAULTCOLOR)
        else:
            hicon = win32gui.CreateIconFromResource(resource, True)
        pixmap = hicon_to_pixmap(hicon).copy()
        win32gui.DestroyIcon(hicon)
    return pixmap
Пример #28
0
def drag_icon(self, cover, multiple):
    cover = cover.scaledToHeight(120, Qt.SmoothTransformation)
    if multiple:
        base_width = cover.width()
        base_height = cover.height()
        base = QImage(base_width+21, base_height+21,
                QImage.Format_ARGB32_Premultiplied)
        base.fill(QColor(255, 255, 255, 0).rgba())
        p = QPainter(base)
        rect = QRect(20, 0, base_width, base_height)
        p.fillRect(rect, QColor('white'))
        p.drawRect(rect)
        rect.moveLeft(10)
        rect.moveTop(10)
        p.fillRect(rect, QColor('white'))
        p.drawRect(rect)
        rect.moveLeft(0)
        rect.moveTop(20)
        p.fillRect(rect, QColor('white'))
        p.save()
        p.setCompositionMode(p.CompositionMode_SourceAtop)
        p.drawImage(rect.topLeft(), cover)
        p.restore()
        p.drawRect(rect)
        p.end()
        cover = base
    return QPixmap.fromImage(cover)
Пример #29
0
    def __init__(self, parent=None):
        QStackedWidget.__init__(self, parent)
        self.welcome = w = QLabel('<p>'+_(
            'Double click a file in the left panel to start editing'
            ' it.'))
        self.addWidget(w)
        w.setWordWrap(True)
        w.setAlignment(Qt.AlignTop | Qt.AlignHCenter)

        self.container = c = QWidget(self)
        self.addWidget(c)
        l = c.l = QVBoxLayout(c)
        c.setLayout(l)
        l.setContentsMargins(0, 0, 0, 0)
        self.editor_tabs = t = QTabWidget(c)
        l.addWidget(t)
        t.setDocumentMode(True)
        t.setTabsClosable(True)
        t.setMovable(True)
        pal = self.palette()
        if pal.color(pal.WindowText).lightness() > 128:
            i = QImage(I('modified.png'))
            i.invertPixels()
            self.modified_icon = QIcon(QPixmap.fromImage(i))
        else:
            self.modified_icon = QIcon(I('modified.png'))
        self.editor_tabs.currentChanged.connect(self.current_editor_changed)
        self.editor_tabs.tabCloseRequested.connect(self._close_requested)
        self.search_panel = SearchPanel(self)
        l.addWidget(self.search_panel)
        self.restore_state()
        self.editor_tabs.tabBar().installEventFilter(self)
Пример #30
0
def test(scale=0.25):
    from PyQt5.Qt import QLabel, QPixmap, QMainWindow, QWidget, QScrollArea, QGridLayout
    from calibre.gui2 import Application
    app = Application([])
    mi = Metadata('Unknown', ['Kovid Goyal', 'John & Doe', 'Author'])
    mi.series = 'A series & styles'
    m = QMainWindow()
    sa = QScrollArea(m)
    w = QWidget(m)
    sa.setWidget(w)
    l = QGridLayout(w)
    w.setLayout(l), l.setSpacing(30)
    scale *= w.devicePixelRatioF()
    labels = []
    for r, color in enumerate(sorted(default_color_themes)):
        for c, style in enumerate(sorted(all_styles())):
            mi.series_index = c + 1
            mi.title = 'An algorithmic cover [%s]' % color
            prefs = override_prefs(cprefs, override_color_theme=color, override_style=style)
            scale_cover(prefs, scale)
            img = generate_cover(mi, prefs=prefs, as_qimage=True)
            img.setDevicePixelRatio(w.devicePixelRatioF())
            la = QLabel()
            la.setPixmap(QPixmap.fromImage(img))
            l.addWidget(la, r, c)
            labels.append(la)
    m.setCentralWidget(sa)
    w.resize(w.sizeHint())
    m.show()
    app.exec_()
Пример #31
0
 def show_data(self, data):
     self.animation.stop()
     same_item = getattr(data, 'id', True) == self.data.get('id', False)
     self.data = {'id':data.get('id', None)}
     if data.cover_data[1]:
         self.pixmap = QPixmap.fromImage(data.cover_data[1])
         if self.pixmap.isNull() or self.pixmap.width() < 5 or \
                 self.pixmap.height() < 5:
             self.pixmap = self.default_pixmap
     else:
         self.pixmap = self.default_pixmap
     self.do_layout()
     self.update()
     if (not same_item and not config['disable_animations'] and
             self.isVisible()):
         self.animation.start()
Пример #32
0
 def layoutChanged(self):
     """SLOT: layoutChanged
             
     Updates the GUI when the layout is changed and initiates the transmission of an instruction to the Metro Mini
             
     Expects:
         none
             
     Connects to:
         QButtonGroup.idClicked (counts)
         QCheckBox.clicked
     """
     self.layout.setPixmap(QPixmap(f"layouts/{self.counts.checkedId()}{'a' if self.alternateLayout.isChecked() else ''}.png").scaled(200, 200, Qt.AspectRatioMode.KeepAspectRatio, \
                                                                                                                                     Qt.TransformationMode.SmoothTransformation))
     self.updateCheckBox()
     self.composeAndSend()
Пример #33
0
class ColorButton(QPushButton):

    changed = pyqtSignal()

    def __init__(self, data, name, text, parent):
        QPushButton.__init__(self, text, parent)
        self.ic = QPixmap(self.iconSize())
        color = data[name]
        self.data, self.name = data, name
        if color is not None:
            self.current_color = read_color(color).color()
            self.ic.fill(self.current_color)
        else:
            self.ic.fill(Qt.GlobalColor.transparent)
            self.current_color = color
        self.update_tooltip()
        self.setIcon(QIcon(self.ic))
        self.clicked.connect(self.choose_color)

    def clear(self):
        self.current_color = None
        self.update_tooltip()
        self.ic.fill(Qt.GlobalColor.transparent)
        self.setIcon(QIcon(self.ic))
        self.data[self.name] = self.value
        self.changed.emit()

    def choose_color(self):
        col = QColorDialog.getColor(self.current_color or Qt.GlobalColor.black, self, _('Choose color'))
        if col.isValid():
            self.current_color = col
            self.update_tooltip()
            self.ic.fill(col)
            self.setIcon(QIcon(self.ic))
            self.data[self.name] = self.value
            self.changed.emit()

    def update_tooltip(self):
        self.setToolTip(_('Red: {0} Green: {1} Blue: {2}').format(*self.current_color.getRgb()[:3]) if self.current_color else _('No color'))

    @property
    def value(self):
        if self.current_color is None:
            return None
        return col_to_string(self.current_color)
Пример #34
0
 def paint(self, painter, option, index):
     QStyledItemDelegate.paint(self, painter, option, index)
     style = QApplication.style()
     waiting = self.timer.isActive() and bool(
         index.data(Qt.ItemDataRole.UserRole))
     if waiting:
         rect = QRect(0, 0, self.spinner_width, self.spinner_width)
         rect.moveCenter(option.rect.center())
         draw_snake_spinner(painter, rect, self.angle, self.light_color,
                            self.dark_color)
     else:
         # Ensure the cover is rendered over any selection rect
         style.drawItemPixmap(
             painter, option.rect,
             Qt.AlignmentFlag.AlignTop | Qt.AlignmentFlag.AlignHCenter,
             QPixmap(index.data(Qt.ItemDataRole.DecorationRole)))
Пример #35
0
 def btn_clicked_select_file(self, window, mobile_phone):
     try:
         file = QFileDialog.getOpenFileName(self)
     except Exception as e:
         print(e)
         return
     filepath = file[0]
     filename = filepath.split("/")[
         -1]  # Se obtiene el nombre del archivo sin ruta.
     temp_path = "images/temp/" + filename
     shutil.copy(filepath, temp_path)
     label_height = window.lbl_image.height()
     image = QPixmap(temp_path).scaledToHeight(label_height)
     window.lbl_image.setPixmap(image)
     mobile_phone.photo_path = temp_path
     return
Пример #36
0
    def create_state_labels(self, state_name):
        """
        Generate 4 QLabel and 1 QProgressBar and store them in "state_data"
        QLabels are: state_icon | state_text | state_number | state_diff
        QProgressBar get value of percent.
        All are added on one row define by "row" value

        :param state_name: name of the state to be stored
        :type state_name: str
        """

        # Icon
        icon = QPixmap(get_image_path(state_name))
        state_icon = QLabel()
        state_icon.setFixedSize(16, 16)
        state_icon.setScaledContents(True)
        state_icon.setPixmap(icon)

        # Initialize Labels
        state_text = QLabel(self.define_label(state_name))
        state_number = QLabel()
        state_diff = QLabel()

        # QProgressBar
        progress_bar = QProgressBar()
        progress_bar.setValue(0)
        progress_bar.setFixedHeight(20)
        progress_bar.setObjectName(state_name)

        # Layout
        self.main_layout.addWidget(state_icon, self.row, 0)
        self.main_layout.addWidget(state_text, self.row, 1)
        self.main_layout.addWidget(state_number, self.row, 2)
        self.main_layout.setAlignment(state_number, Qt.AlignCenter)
        self.main_layout.addWidget(state_diff, self.row, 3)
        self.main_layout.addWidget(progress_bar, self.row, 4)

        # Store state
        self.state_data[state_name] = {
            'icon': state_icon,
            'state_number': state_number,
            'diff': state_diff,
            'progress_bar': progress_bar
        }

        # Increment vertically position for next widget
        self.row += 1
Пример #37
0
    def __init__(self,
                 msg,
                 name,
                 parent,
                 config_set=dynamic,
                 icon='dialog_warning.png',
                 title=None,
                 confirm_msg=None,
                 show_cancel_button=True):
        QDialog.__init__(self, parent)
        self.setWindowTitle(title or _("Are you sure?"))
        self.setWindowIcon(QIcon(I(icon)))
        self.l = l = QVBoxLayout(self)
        self.h = h = QHBoxLayout()
        l.addLayout(h)

        self.label = la = QLabel(self)
        la.setScaledContents(True), la.setMaximumSize(QSize(
            96, 96)), la.setMinimumSize(QSize(96, 96))
        la.setPixmap(QPixmap(I(icon)))
        la.setObjectName("label")

        self.msg = m = QLabel(self)
        m.setMinimumWidth(300), m.setWordWrap(True), m.setObjectName("msg")
        m.setText(msg)

        h.addWidget(la), h.addSpacing(10), h.addWidget(m)

        self.again = a = QCheckBox(
            (confirm_msg or _("&Show this warning again")), self)
        a.setChecked(True), a.setObjectName("again")
        a.stateChanged.connect(self.toggle)
        l.addWidget(a)

        buttons = QDialogButtonBox.Ok
        if show_cancel_button:
            buttons |= QDialogButtonBox.Cancel
        self.buttonBox = bb = QDialogButtonBox(buttons, self)
        bb.setObjectName("buttonBox")
        bb.setFocus(Qt.OtherFocusReason)
        bb.accepted.connect(self.accept), bb.rejected.connect(self.reject)
        l.addWidget(bb)

        self.name = name
        self.config_set = config_set

        self.resize(self.sizeHint())
Пример #38
0
    def createThumbnail(self, status):
        '''
        @param: status bool
        '''
        if not status:
            self.thumbnailCreated.emit(QPixmap())
            return

        def func():
            self._title = self._view.rootObject().property('title').strip()
            img = self._view.grabFramebuffer().scaled(self._size,
                                                      Qt.IgnoreAspectRatio,
                                                      Qt.SmoothTransformation)
            pixmap = QPixmap.fromImage(img)
            self.thumbnailCreated.emit(pixmap)

        QTimer.singleShot(1000, func)
Пример #39
0
    def setPhototoView(self,img):
        h = self.lbl_photo_view.height()
        w = self.lbl_photo_view.width()

        img_h = img.height()
        img_w = img.width()
        if (img_h > img_w):
            scale_factor = h / img_h
            img_h = h
            img_w *= scale_factor
        else:
            scale_factor = w / img_w
            img_w = w
            img_h *= scale_factor
        image = img.scaledToHeight(img_h)
        # img.scaledToWidth(img_w)
        self.lbl_photo_view.setPixmap(QPixmap.fromImage(image))
Пример #40
0
 def load_pixmap(self):
     canvas_size = self.rect().width(), self.rect().height()
     if self.last_canvas_size != canvas_size:
         if self.last_canvas_size is not None and self.selection_state.rect is not None:
             self.selection_state.reset()
             # TODO: Migrate the selection rect
         self.last_canvas_size = canvas_size
         self.current_scaled_pixmap = None
     if self.current_scaled_pixmap is None:
         pwidth, pheight = self.last_canvas_size
         i = self.current_image
         width, height = i.width(), i.height()
         scaled, width, height = fit_image(width, height, pwidth, pheight)
         if scaled:
             i = self.current_image.scaled(
                 width, height, transformMode=Qt.SmoothTransformation)
         self.current_scaled_pixmap = QPixmap.fromImage(i)
Пример #41
0
 def initialize(self):
     """METHOD: initialize
             
     Sends initial settings to the Metro Mini (calls patternChanged as a method)
             
     Called by:
         MainWindow.initializeSerialObjects
             
     Arguments:
         none
             
     Returns:
         none
     """
     self.layout.setPixmap(QPixmap(f"layouts/{self.counts.checkedId()}{'a' if self.alternateLayout.isChecked() else ''}.png").scaled(200, 200, Qt.AspectRatioMode.KeepAspectRatio, \
                                                                                                                                     Qt.TransformationMode.SmoothTransformation))
     self.patternChanged(self.patterns.checkedId())
Пример #42
0
    def get_logo_widget(widget):
        """
        Return the logo QWidget

        :param widget: widget parent, needed for action button
        :type widget: QWidget
        :return: logo QWidget
        :rtype: QWidget
        """

        logo_widget = QWidget()
        logo_widget.setFixedHeight(45)
        logo_widget.setObjectName('title')
        logo_layout = QHBoxLayout()
        logo_widget.setLayout(logo_layout)

        logo_label = QLabel()
        logo_label.setPixmap(QPixmap(get_image_path('alignak')))
        logo_label.setFixedSize(121, 35)
        logo_label.setScaledContents(True)

        logo_layout.addWidget(logo_label, 0)

        minimize_btn = QPushButton()
        minimize_btn.setIcon(QIcon(get_image_path('minimize')))
        minimize_btn.setFixedSize(24, 24)
        minimize_btn.setObjectName('app_widget')
        minimize_btn.clicked.connect(widget.showMinimized)
        logo_layout.addStretch(widget.width())
        logo_layout.addWidget(minimize_btn, 1)

        maximize_btn = QPushButton()
        maximize_btn.setIcon(QIcon(get_image_path('maximize')))
        maximize_btn.setFixedSize(24, 24)
        maximize_btn.setObjectName('app_widget')
        maximize_btn.clicked.connect(widget.showMaximized)
        logo_layout.addWidget(maximize_btn, 2)

        close_btn = QPushButton()
        close_btn.setIcon(QIcon(get_image_path('exit')))
        close_btn.setObjectName('app_widget')
        close_btn.setFixedSize(24, 24)
        close_btn.clicked.connect(widget.close)
        logo_layout.addWidget(close_btn, 3)

        return logo_widget
Пример #43
0
    def paint(self, painter, option, index):
        QStyledItemDelegate.paint(
            self, painter, option,
            QModelIndex())  # draw the hover and selection highlights
        name = unicode(index.data(Qt.DisplayRole) or '')
        cover = self.cover_cache.get(name, None)
        if cover is None:
            cover = self.cover_cache[name] = QPixmap()
            try:
                raw = current_container().raw_data(name, decode=False)
            except:
                pass
            else:
                cover.loadFromData(raw)
                if not cover.isNull():
                    scaled, width, height = fit_image(cover.width(),
                                                      cover.height(),
                                                      self.cover_size.width(),
                                                      self.cover_size.height())
                    if scaled:
                        cover = self.cover_cache[name] = cover.scaled(
                            width,
                            height,
                            transformMode=Qt.SmoothTransformation)

        painter.save()
        try:
            rect = option.rect
            rect.adjust(self.MARGIN, self.MARGIN, -self.MARGIN, -self.MARGIN)
            trect = QRect(rect)
            rect.setBottom(rect.bottom() - self.title_height)
            if not cover.isNull():
                dx = max(0, int((rect.width() - cover.width()) / 2.0))
                dy = max(0, rect.height() - cover.height())
                rect.adjust(dx, dy, -dx, 0)
                painter.drawPixmap(rect, cover)
            rect = trect
            rect.setTop(rect.bottom() - self.title_height + 5)
            painter.setRenderHint(QPainter.TextAntialiasing, True)
            metrics = painter.fontMetrics()
            painter.drawText(
                rect, Qt.AlignCenter | Qt.TextSingleLine,
                metrics.elidedText(name, Qt.ElideLeft, rect.width()))
        finally:
            painter.restore()
Пример #44
0
 def __init__(self, parent=None):
     QTreeWidget.__init__(self, parent)
     self.categories = {}
     self.ordered_selected_indexes = False
     pi = plugins['progress_indicator'][0]
     if hasattr(pi, 'set_no_activate_on_click'):
         pi.set_no_activate_on_click(self)
     self.current_edited_name = None
     self.delegate = ItemDelegate(self)
     self.delegate.rename_requested.connect(self.rename_requested)
     self.setTextElideMode(Qt.ElideMiddle)
     self.setItemDelegate(self.delegate)
     self.setIconSize(QSize(16, 16))
     self.header().close()
     self.setDragEnabled(True)
     self.setEditTriggers(self.EditKeyPressed)
     self.setSelectionMode(self.ExtendedSelection)
     self.viewport().setAcceptDrops(True)
     self.setDropIndicatorShown(True)
     self.setDragDropMode(self.InternalMove)
     self.setAutoScroll(True)
     self.setAutoScrollMargin(TOP_ICON_SIZE * 2)
     self.setDefaultDropAction(Qt.MoveAction)
     self.setAutoExpandDelay(1000)
     self.setAnimated(True)
     self.setMouseTracking(True)
     self.setContextMenuPolicy(Qt.CustomContextMenu)
     self.customContextMenuRequested.connect(self.show_context_menu)
     self.root = self.invisibleRootItem()
     self.emblem_cache = {}
     self.rendered_emblem_cache = {}
     self.top_level_pixmap_cache = {
         name:
         QPixmap(I(icon)).scaled(TOP_ICON_SIZE,
                                 TOP_ICON_SIZE,
                                 transformMode=Qt.SmoothTransformation)
         for name, icon in {
             'text': 'keyboard-prefs.png',
             'styles': 'lookfeel.png',
             'fonts': 'font.png',
             'misc': 'mimetypes/dir.png',
             'images': 'view-image.png',
         }.iteritems()
     }
     self.itemActivated.connect(self.item_double_clicked)
Пример #45
0
def create_icon(text, palette=None, sz=None, divider=2, fill='white'):
    if isinstance(fill, str):
        fill = QColor(fill)
    sz = sz or int(math.ceil(tprefs['toolbar_icon_size'] * QApplication.instance().devicePixelRatio()))
    if palette is None:
        palette = QApplication.palette()
    img = QImage(sz, sz, QImage.Format_ARGB32)
    img.fill(Qt.transparent)
    p = QPainter(img)
    p.setRenderHints(p.TextAntialiasing | p.Antialiasing)
    if fill is not None:
        qDrawShadeRect(p, img.rect(), palette, fill=fill, lineWidth=1, midLineWidth=1)
    f = p.font()
    f.setFamily('Liberation Sans'), f.setPixelSize(int(sz // divider)), f.setBold(True)
    p.setFont(f), p.setPen(Qt.black)
    p.drawText(img.rect().adjusted(2, 2, -2, -2), Qt.AlignCenter, text)
    p.end()
    return QIcon(QPixmap.fromImage(img))
Пример #46
0
def seleccionar_imagen():  #selección de imagen de ventana de registro
    imagen = QFileDialog.getOpenFileName(
        MainWindow
    )  #explorador para seleccionar imagen, guarda en var imagen su ruta
    ruta_imagen = imagen[
        0]  #la ruta está en el primer elemento de una lista de tuplas
    try:  #prueba lo siguiente para que no se cierre la aplicación si se cancela el explorador de selección de imagen
        shutil.copy(
            ruta_imagen,
            "temp/img_temp.jpg")  #se copia la imagen al directorio temp
        vr.lbl_imagen.setStyleSheet("*{background-image: url("
                                    "); border:1px solid #32414B;}")
        pixmap = QPixmap("temp/img_temp.jpg")
        vr.lbl_imagen.setScaledContents(True)
        vr.lbl_imagen.setPixmap(
            pixmap)  #muestra imagen seleccionada en el lbl_imagen
    except:
        sys.exc_info()
Пример #47
0
 def loop(self):
     if self.ready and self.isOpened:
         frame = self.cap.read()
         if frame[0] == True:
             frame_1 = cv2.resize(frame[1], (600, 480))
             frame_2 = cv2.cvtColor(frame_1, cv2.COLOR_BGR2RGB)
             image = QImage(frame_2, frame_2.shape[1], frame_2.shape[0],
                            frame_2.strides[0], QImage.Format_RGB888)
             self.label_display.setPixmap(QPixmap.fromImage(image))
             new_img = imresize(frame_1, (64, 64, 3))
             self.allX[0] = np.array(new_img)
             result = self.model.predict(self.allX)
             self.label_result.setText(selectBestBiger(result[0]))
         else:
             self.btn_start.setText('Start')
             self.btn_text = 'Start'
             self.ready = False
             self.cap = cv2.VideoCapture(self.fileName)
Пример #48
0
    def show_window_list_with_tablewidget(self):
        self.window_list_with_tablewidget.setupUi(self)
        try:
            mobiles_list = db_operations.get_mobile_phones()
        except Exception as e:
            print(e)
            return
        row = 0
        for mobile_phone in mobiles_list:
            self.window_list_with_tablewidget.tbl_list.insertRow(row)
            cell = QTableWidgetItem(str(mobile_phone.id_mobile_phone))
            self.window_list_with_tablewidget.tbl_list.setItem(row, 0, cell)
            cell = QTableWidgetItem(mobile_phone.brand)
            self.window_list_with_tablewidget.tbl_list.setItem(row, 1, cell)
            cell = QTableWidgetItem(mobile_phone.model)
            self.window_list_with_tablewidget.tbl_list.setItem(row, 2, cell)
            cell = QTableWidgetItem(mobile_phone.os)
            self.window_list_with_tablewidget.tbl_list.setItem(row, 3, cell)
            cell = QTableWidgetItem(str(mobile_phone.memory))
            self.window_list_with_tablewidget.tbl_list.setItem(row, 4, cell)
            cell = QTableWidgetItem(str(mobile_phone.price))
            self.window_list_with_tablewidget.tbl_list.setItem(row, 5, cell)
            cell = QTableWidgetItem(str(mobile_phone.deal))
            self.window_list_with_tablewidget.tbl_list.setItem(row, 6, cell)
            cell = QTableWidgetItem(str(mobile_phone.technology))
            self.window_list_with_tablewidget.tbl_list.setItem(row, 7, cell)
            try:
                if pathlib.Path(mobile_phone.photo_path).is_file():
                    image = QLabel()
                    pixmap = QPixmap(
                        mobile_phone.photo_path).scaledToHeight(50)
                    image.setPixmap(pixmap)
                    self.window_list_with_tablewidget.tbl_list.setCellWidget(
                        row, 8, image)
            except Exception as e:
                print(e)
                return

            row += 1
        self.window_list_with_tablewidget.btn_delete.clicked.connect(
            self.btn_clicked_delete)
        self.window_list_with_tablewidget.btn_update.clicked.connect(
            self.btn_clicked_update)
        return
Пример #49
0
 def update_cover(self, pmap=None, cdata=None):
     if pmap is None:
         pmap = QPixmap()
         pmap.loadFromData(cdata)
     if pmap.isNull():
         return
     if pmap.hasAlphaChannel():
         pmap = QPixmap.fromImage(blend_image(image_from_x(pmap)))
     self.pixmap = pmap
     self.do_layout()
     self.update()
     self.update_tooltip(getattr(self.parent(), 'current_path', ''))
     if not config['disable_animations']:
         self.animation.start()
     id_ = self.data.get('id', None)
     if id_ is not None:
         self.cover_changed.emit(id_, cdata or pixmap_to_data(pmap))
Пример #50
0
class ImagePopup(object):
    def __init__(self, parent):
        self.current_img = QPixmap()
        self.current_url = QUrl()
        self.parent = parent
        self.dialogs = []

    def __call__(self):
        if self.current_img.isNull():
            return
        d = ImageView(self.parent, self.current_img, self.current_url)
        self.dialogs.append(d)
        d.finished.connect(self.cleanup, type=Qt.QueuedConnection)
        d()

    def cleanup(self):
        for d in tuple(self.dialogs):
            if not d.isVisible():
                self.dialogs.remove(d)
    def on_pb_camera1_clicked(self):
        """从摄像头拍照 处理函数"""
        idNo = self.le_idNum.text()
        self.dlg = collectImgController.CollectImgWindow()
        self.dlg.idNo = idNo
        if self.dlg.exec_() == QDialog.Accepted:
            self.dlg.destroy()
            srcImg = './photos_face/{}.jpg'.format(self.dlg.idNo)
            dstImg = './photos_face/{}_face.jpg'.format(self.dlg.idNo)
            r = self.face.getFacePos(srcImg, dstImg)
            if r:
                img = QPixmap(dstImg)

                self.lb_photo3.setPixmap(img)
            else:
                QMessageBox.information(self, '提示', '图片中未检测到头像,请重试!',
                                        QMessageBox.Yes)
        else:
            pass
Пример #52
0
    def slotDeleteUser(self):
        if self.ui.userList.currentRow() == self.edititemindex:
            self.resetWidgets()
            self.ui.autoLogin.setCurrentIndex(0)
        _cur = self.ui.userList.currentRow()
        item = self.ui.userList.item(_cur).getUser()
        if item.uid in self.used_ids:
            self.used_ids.remove(item.uid)
        self.ui.userList.takeItem(_cur)
        self.ui.autoLogin.removeItem(_cur + 1)
        self.ui.createButton.setText(_("Add"))

        icon = QIcon()
        icon.addPixmap(QPixmap(":/gui/pics/user-group-new.png"), QIcon.Normal,
                       QIcon.Off)
        self.ui.createButton.setIcon(icon)

        self.ui.cancelButton.hide()
        self.checkUsers()
Пример #53
0
    def _set_up_frame_ui(self):
        self.up_frame = QFrame()
        self.up_frame.setMinimumHeight(300)
        self.up_frame.setMaximumHeight(500)
        self.up_layout = QHBoxLayout(self.up_frame)
        up_left_frame = QFrame()
        # up_left_frame.setMinimumWidth(self.main_ui.window.geometry().width() / 2)
        # up_left_frame.setMaximumWidth(self.geometry().width() / 2)
        up_right_frame = QFrame()
        # up_right_frame.setMinimumWidth(self.main_ui.window.geometry().width() / 2)
        # up_right_frame.setMaximumWidth(self.geometry().width() / 2)
        self.up_left_layout = QHBoxLayout(up_left_frame)
        self.up_right_layout = QHBoxLayout(up_right_frame)
        self.up_layout.addWidget(up_left_frame)
        # self.up_layout.addWidget(up_right_frame)
        self.layout.addWidget(self.up_frame)

        self.label_img = QLabel()
        # self.label_img.setMaximumHeight(320)
        # self.label_img.setMaximumWidth(480)
        # self.label_img.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Ignored)
        # self.label_img.setScaledContents(True)

        img = QImage()
        if img.load(os.path.join(icon_path, 'tmp.svg')):
            self.label_img.setPixmap(QPixmap.fromImage(img))
            with open(os.path.join(icon_path, 'tmp.svg'), 'rb') as f:
                self.handler.source = f.read()

        self.up_left_layout.addWidget(self.label_img)

        self.label_img_preview = QLabel()
        # self.label_img_preview.setMaximumHeight(320)
        # self.label_img_preview.setMaximumWidth(480)
        self.label_img_preview.setDisabled(True)
        # # self.label_img_preview.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Ignored)
        # # self.label_img_preview.setScaledContents(True)
        # data = np.zeros(320 * 240)
        # img = QImage(data, 320, 240, QImage.Format_RGB888)
        # pixmap = QPixmap.fromImage(img)
        # self.label_img_preview.setPixmap(pixmap)
        self.up_right_layout.addWidget(self.label_img_preview)
Пример #54
0
 def __init__(self, calibre_version, plugin_updates, parent=None):
     QDialog.__init__(self, parent)
     self.setAttribute(Qt.WA_QuitOnClose, False)
     self.resize(400, 250)
     self.l = QGridLayout()
     self.setLayout(self.l)
     self.logo = QLabel()
     self.logo.setMaximumWidth(110)
     self.logo.setPixmap(QPixmap(I('lt.png')).scaled(100, 100,
         Qt.IgnoreAspectRatio, Qt.SmoothTransformation))
     ver = calibre_version
     if ver.endswith('.0'):
         ver = ver[:-2]
     self.label = QLabel(('<p>'+
         _('New version <b>%(ver)s</b> of %(app)s is available for download. '
         'See the <a href="https://calibre-ebook.com/whats-new'
         '">new features</a>.'))%dict(
             app=__appname__, ver=ver))
     self.label.setOpenExternalLinks(True)
     self.label.setWordWrap(True)
     self.setWindowTitle(_('Update available!'))
     self.setWindowIcon(QIcon(I('lt.png')))
     self.l.addWidget(self.logo, 0, 0)
     self.l.addWidget(self.label, 0, 1)
     self.cb = QCheckBox(
         _('Show this notification for future updates'), self)
     self.l.addWidget(self.cb, 1, 0, 1, -1)
     self.cb.setChecked(config.get('new_version_notification'))
     self.cb.stateChanged.connect(self.show_future)
     self.bb = QDialogButtonBox(self)
     b = self.bb.addButton(_('&Get update'), self.bb.AcceptRole)
     b.setDefault(True)
     b.setIcon(QIcon(I('arrow-down.png')))
     if plugin_updates > 0:
         b = self.bb.addButton(_('Update &plugins'), self.bb.ActionRole)
         b.setIcon(QIcon(I('plugins/plugin_updater.png')))
         b.clicked.connect(self.get_plugins, type=Qt.QueuedConnection)
     self.bb.addButton(self.bb.Cancel)
     self.l.addWidget(self.bb, 2, 0, 1, -1)
     self.bb.accepted.connect(self.accept)
     self.bb.rejected.connect(self.reject)
     dynamic.set('update to version %s'%calibre_version, False)
Пример #55
0
 def resetWidgets(self):
     # clear all
     self.edititemindex = None
     self.ui.username.clear()
     self.ui.realname.clear()
     self.ui.pass1.clear()
     self.ui.pass2.clear()
     self.ui.admin.setChecked(False)
     self.ui.noPass.setChecked(False)
     self.ui.userIDCheck.setChecked(False)
     self.ui.createButton.setEnabled(False)
     if self.ui.cancelButton.isVisible():
         self.ui.cancelButton.setHidden(
             self.sender() == self.ui.cancelButton)
         self.checkUsers()
     self.ui.createButton.setText(_("Add"))
     icon = QIcon()
     icon.addPixmap(QPixmap(":/gui/pics/user-group-new.png"), QIcon.Normal,
                    QIcon.Off)
     self.ui.createButton.setIcon(icon)
Пример #56
0
    def get_host_icon(host):
        """
        Return QPixmap with the icon corresponding to the status.

        :param host: host data from AppBackend
        :type host: dict
        :return: QPixmap with image
        :rtype: QPixmap
        """

        if host['ls_acknowledged']:
            icon_name = 'hosts_acknowledge'
        elif host['ls_downtimed']:
            icon_name = 'hosts_downtimed'
        else:
            icon_name = 'hosts_%s' % host['ls_state'].lower()

        icon = QPixmap(get_image_path(icon_name))

        return icon
Пример #57
0
def create_icon(text, palette=None, sz=32, divider=2):
    if palette is None:
        palette = QApplication.palette()
    img = QImage(sz, sz, QImage.Format_ARGB32)
    img.fill(Qt.transparent)
    p = QPainter(img)
    p.setRenderHints(p.TextAntialiasing | p.Antialiasing)
    qDrawShadeRect(p,
                   img.rect(),
                   palette,
                   fill=QColor('#ffffff'),
                   lineWidth=1,
                   midLineWidth=1)
    f = p.font()
    f.setFamily('Liberation Sans'), f.setPixelSize(sz //
                                                   divider), f.setBold(True)
    p.setFont(f), p.setPen(Qt.black)
    p.drawText(img.rect().adjusted(2, 2, -2, -2), Qt.AlignCenter, text)
    p.end()
    return QIcon(QPixmap.fromImage(img))
Пример #58
0
 def failed_img(self):
     if self._failed_img is None:
         i = QImage(200, 150, QImage.Format_ARGB32)
         i.fill(Qt.white)
         p = QPainter(i)
         r = i.rect().adjusted(10, 10, -10, -10)
         n = QPen(Qt.DashLine)
         n.setColor(Qt.black)
         p.setPen(n)
         p.drawRect(r)
         p.setPen(Qt.black)
         f = self.font()
         f.setPixelSize(20)
         p.setFont(f)
         p.drawText(r.adjusted(10, 0, -10, 0),
                    Qt.AlignCenter | Qt.TextWordWrap,
                    _('Image could not be rendered'))
         p.end()
         self._failed_img = QPixmap.fromImage(i)
     return self._failed_img
Пример #59
0
 def load_pixmap(self):
     canvas_size = self.rect().width(), self.rect().height()
     if self.last_canvas_size != canvas_size:
         if self.last_canvas_size is not None and self.selection_state.rect is not None:
             self.selection_state.reset()
             # TODO: Migrate the selection rect
         self.last_canvas_size = canvas_size
         self.current_scaled_pixmap = None
     if self.current_scaled_pixmap is None:
         pwidth, pheight = self.last_canvas_size
         i = self.current_image
         width, height = i.width(), i.height()
         scaled, width, height = fit_image(width, height, pwidth, pheight)
         try:
             dpr = self.devicePixelRatioF()
         except AttributeError:
             dpr = self.devicePixelRatio()
         if scaled:
             i = self.current_image.scaled(int(dpr * width), int(dpr * height), transformMode=Qt.SmoothTransformation)
         self.current_scaled_pixmap = QPixmap.fromImage(i)
         self.current_scaled_pixmap.setDevicePixelRatio(dpr)
Пример #60
0
    def __init__(self, vertical, parent=None):
        QWidget.__init__(self, parent)
        self._current_pixmap_size = QSize(120, 120)
        self.vertical = vertical

        self.animation = QPropertyAnimation(self, b'current_pixmap_size', self)
        self.animation.setEasingCurve(QEasingCurve(QEasingCurve.OutExpo))
        self.animation.setDuration(1000)
        self.animation.setStartValue(QSize(0, 0))
        self.animation.valueChanged.connect(self.value_changed)

        self.setSizePolicy(
                QSizePolicy.Expanding if vertical else QSizePolicy.Minimum,
                QSizePolicy.Expanding)

        self.default_pixmap = QPixmap(I('default_cover.png'))
        self.pixmap = self.default_pixmap
        self.pwidth = self.pheight = None
        self.data = {}

        self.do_layout()