Пример #1
0
    def __init__(self, vertical, parent):
        QLayout.__init__(self, parent)
        self.vertical = vertical
        self._children = []

        self.min_size = QSize(190, 200) if vertical else QSize(120, 120)
        self.setContentsMargins(0, 0, 0, 0)
Пример #2
0
 def set_normal_icon_size(self, w, h):
     self.normal_icon_size = QSize(w, h)
     self.setIconSize(self.normal_icon_size)
     try:
         self.setMinimumSize(self.sizeHint())
     except:
         self.setMinimumSize(QSize(w + 5, h + 5))
    def _addToTab(self, submission, submissionURL, lst):
        """
        Add a submission and its representative image to the lst under its tab.

        :type submission: praw.objects.Submission
        :type submissionURL: str
        :type lst: QListWidget
        """
        imagePath = submission.representativeImage
        if imagePath is not None and imagePath.exists():
            item = QListWidgetItem(submissionURL, lst)
            item.setTextColor(Qt.transparent)
            labelWidget = QLabel()
            labelWidget.setOpenExternalLinks(True)
            labelWidget.setTextFormat(Qt.RichText)
            size = QSize(128, 158)
            item.setSizeHint(size)
            size = QSize(128, 128)
            if imagePath.suffix == ".webm":
                imagePath = pathlib.Path("RedditDataExtractor", "images",
                                         "videoImage.png").resolve()
            pixmap = QPixmap(str(imagePath))
            pixmap = pixmap.scaled(size, Qt.KeepAspectRatio)
            height = pixmap.height()
            width = pixmap.width()
            submissionTitle = submissionURL[submissionURL[0:-1].rfind("/") +
                                            1:-1]
            labelWidget.setText('<a href="' + submissionURL + '"><img src="' +
                                str(imagePath) + '" height="' + str(height) +
                                '" width="' + str(width) + '"><p>' +
                                submissionTitle)
            lst.setItemWidget(item, labelWidget)
Пример #4
0
    def __init__(self, pdfpath, parent=None):
        QDialog.__init__(self, parent)
        self.pdfpath = pdfpath
        self.l = l = QGridLayout()
        self.setLayout(l)

        self.la = la = QLabel(
            _('Choose a cover from the list of PDF pages below'))
        l.addWidget(la)
        self.loading = la = QLabel('<b>' +
                                   _('Rendering PDF pages, please wait...'))
        l.addWidget(la)

        self.covers = c = QListWidget(self)
        l.addWidget(c)
        c.setIconSize(QSize(120, 160))
        c.setSelectionMode(c.SingleSelection)
        c.setViewMode(c.IconMode)
        c.setUniformItemSizes(True)
        c.setResizeMode(c.Adjust)
        c.itemDoubleClicked.connect(self.accept)

        self.bb = bb = QDialogButtonBox(QDialogButtonBox.Ok
                                        | QDialogButtonBox.Cancel)
        bb.accepted.connect(self.accept)
        bb.rejected.connect(self.reject)
        l.addWidget(bb)
        self.rendering_done.connect(self.show_pages, type=Qt.QueuedConnection)
        self.tdir = PersistentTemporaryDirectory('_pdf_covers')
        self.thread = Thread(target=self.render)
        self.thread.daemon = True
        self.thread.start()
        self.setWindowTitle(_('Choose cover from PDF'))
        self.setWindowIcon(file_icon_provider().icon_from_ext('pdf'))
        self.resize(QSize(800, 600))
Пример #5
0
    def _createToolButton(self, widgetParams):
        """
        Returns a tool button created using the custom parameters. 
                
        @param widgetParams: A list containing tool button parameters. 
        @type  widgetParams: list
        
        @see: L{self._createWidgetUsingParameters} where this method is called.
        """

        buttonSize = QSize(32, 32)  #@ FOR TEST ONLY

        buttonParams = list(widgetParams)
        buttonId = buttonParams[1]
        buttonText = buttonParams[2]
        buttonIconPath = buttonParams[3]
        buttonToolTip = buttonParams[4]
        buttonShortcut = buttonParams[5]

        button = QToolButton(self)
        button.setText(buttonText)
        if buttonIconPath:
            buttonIcon = geticon(buttonIconPath)
            if not buttonIcon.isNull():
                button.setIcon(buttonIcon)
                button.setIconSize(QSize(22, 22))
        button.setToolTip(buttonToolTip)
        if buttonShortcut:
            button.setShortcut(buttonShortcut)

        button.setFixedSize(buttonSize)  #@ Currently fixed to 32 x 32.
        button.setCheckable(True)
        return button
Пример #6
0
    def set_dimensions(self):
        width = self.original_width = gprefs['cover_grid_width']
        height = self.original_height = gprefs['cover_grid_height']
        self.original_show_title = show_title = gprefs['cover_grid_show_title']

        if height < 0.1:
            height = auto_height(self.parent())
        else:
            height *= self.parent().logicalDpiY() * CM_TO_INCH

        if width < 0.1:
            width = 0.75 * height
        else:
            width *= self.parent().logicalDpiX() * CM_TO_INCH
        self.cover_size = QSize(width, height)
        self.title_height = 0
        if show_title:
            f = self.parent().font()
            sz = f.pixelSize()
            if sz < 5:
                sz = f.pointSize() * self.parent().logicalDpiY() / 72.0
            self.title_height = max(25, sz + 10)
        self.item_size = self.cover_size + QSize(
            2 * self.MARGIN, (2 * self.MARGIN) + self.title_height)
        self.calculate_spacing()
        self.animation.setStartValue(1.0)
        self.animation.setKeyValueAt(0.5, 0.5)
        self.animation.setEndValue(1.0)
Пример #7
0
    def __init__(self, img_data, parent=None):
        QDialog.__init__(self, parent)
        self.l = l = QGridLayout(self)
        self.setLayout(l)
        self.setWindowTitle(_('Trim Image'))

        self.bar = b = QToolBar(self)
        l.addWidget(b)
        b.setToolButtonStyle(Qt.ToolButtonTextBesideIcon)
        b.setIconSize(QSize(32, 32))

        self.msg = la = QLabel('\xa0' + _(
            'Select a region by dragging with your mouse on the image, and then click trim'
        ))
        self.sz = QLabel('')

        self.canvas = c = Canvas(self)
        c.image_changed.connect(self.image_changed)
        c.load_image(img_data)
        self.undo_action = u = c.undo_action
        u.setShortcut(QKeySequence(QKeySequence.Undo))
        self.redo_action = r = c.redo_action
        r.setShortcut(QKeySequence(QKeySequence.Redo))
        self.trim_action = ac = self.bar.addAction(QIcon(I('trim.png')),
                                                   _('&Trim'), c.trim_image)
        ac.setShortcut(QKeySequence('Ctrl+T'))
        ac.setToolTip(
            '%s [%s]' %
            (_('Trim image by removing borders outside the selected region'),
             ac.shortcut().toString(QKeySequence.NativeText)))
        ac.setEnabled(False)
        c.selection_state_changed.connect(self.selection_changed)
        l.addWidget(c)
        self.bar.addAction(self.trim_action)
        self.bar.addSeparator()
        self.bar.addAction(u)
        self.bar.addAction(r)
        self.bar.addSeparator()
        self.bar.addWidget(la)
        self.bar.addSeparator()
        self.bar.addWidget(self.sz)

        self.bb = bb = QDialogButtonBox(QDialogButtonBox.Ok
                                        | QDialogButtonBox.Cancel)
        bb.accepted.connect(self.accept)
        bb.rejected.connect(self.reject)
        l.addWidget(bb)

        self.tok = b = bb.addButton(_('Trim and OK'),
                                    QDialogButtonBox.ActionRole)
        b.clicked.connect(self.trim_and_accept)
        b.setIcon(self.trim_action.icon())

        self.resize(QSize(900, 600))
        geom = gprefs.get('image-trim-dialog-geometry', None)
        if geom is not None:
            self.restoreGeometry(geom)
        self.setWindowIcon(self.trim_action.icon())
        self.image_data = None
Пример #8
0
 def update_tooltip(self, current_path):
     try:
         sz = self.pixmap.size()
     except:
         sz = QSize(0, 0)
     self.setToolTip('<p>' + _('Double-click to open Book Details window') +
                     '<br><br>' + _('Path') + ': ' + current_path +
                     '<br><br>' + _('Cover size: %(width)d x %(height)d') %
                     dict(width=sz.width(), height=sz.height()))
Пример #9
0
    def __init__(self, parent=None, initial=None):
        QDialog.__init__(self, parent)
        self.setWindowTitle(_('Choose a texture'))

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

        self.tdir = texture_dir()

        self.images = il = QListWidget(self)
        il.itemDoubleClicked.connect(self.accept, type=Qt.QueuedConnection)
        il.setIconSize(QSize(256, 256))
        il.setViewMode(il.IconMode)
        il.setFlow(il.LeftToRight)
        il.setSpacing(20)
        il.setSelectionMode(il.SingleSelection)
        il.itemSelectionChanged.connect(self.update_remove_state)
        l.addWidget(il)

        self.ad = ad = QLabel(_('The builtin textures come from <a href="http://subtlepatterns.com">subtlepatterns.com</a>.'))
        ad.setOpenExternalLinks(True)
        ad.setWordWrap(True)
        l.addWidget(ad)
        self.bb = bb = QDialogButtonBox(QDialogButtonBox.Ok|QDialogButtonBox.Cancel)
        bb.accepted.connect(self.accept)
        bb.rejected.connect(self.reject)
        b = self.add_button = bb.addButton(_('Add texture'), bb.ActionRole)
        b.setIcon(QIcon(I('plus.png')))
        b.clicked.connect(self.add_texture)
        b = self.remove_button = bb.addButton(_('Remove texture'), bb.ActionRole)
        b.setIcon(QIcon(I('minus.png')))
        b.clicked.connect(self.remove_texture)
        l.addWidget(bb)

        images = [{
            'fname': ':'+os.path.basename(x),
            'path': x,
            'name': ' '.join(map(string.capitalize, os.path.splitext(os.path.basename(x))[0].split('_')))
        } for x in glob.glob(I('textures/*.png'))] + [{
            'fname': os.path.basename(x),
            'path': x,
            'name': os.path.splitext(os.path.basename(x))[0],
        } for x in glob.glob(os.path.join(self.tdir, '*')) if x.rpartition('.')[-1].lower() in {'jpeg', 'png', 'jpg'}]

        images.sort(key=lambda x:sort_key(x['name']))

        map(self.create_item, images)
        self.update_remove_state()

        if initial:
            existing = {unicode(i.data(Qt.UserRole).toString()):i for i in (self.images.item(c) for c in xrange(self.images.count()))}
            item = existing.get(initial, None)
            if item is not None:
                item.setSelected(True)
                QTimer.singleShot(100, partial(il.scrollToItem, item))

        self.resize(QSize(950, 650))
Пример #10
0
 def __init__(self, *args):
     QToolButton.__init__(self, *args)
     self.animation = QPropertyAnimation(self, 'iconSize', self)
     self.animation.setDuration(60 / 72. * 1000)
     self.animation.setLoopCount(4)
     self.normal_icon_size = QSize(64, 64)
     self.animation.valueChanged.connect(self.value_changed)
     self.setCursor(Qt.PointingHandCursor)
     self.animation.finished.connect(self.animation_finished)
    def _loadLayerPropertiesGroupBox(self, inPmGroupBox):
        """
        Load widgets in the Layer Properties group box.
        @param inPmGroupBox: The Layer Properties groupbox in the PM
        @type  inPmGroupBox: L{PM_GroupBox} 
        """

        self.currentLayerComboBox = \
            PM_ComboBox( inPmGroupBox,
                         index     = 0,
                         spanWidth = True
                        )

        self.addLayerButton = PM_PushButton(inPmGroupBox)
        self.addLayerButton.setIcon(
            geticon('ui/actions/Properties Manager/addlayer.png'))
        self.addLayerButton.setFixedSize(QSize(26, 26))
        self.addLayerButton.setIconSize(QSize(22, 22))

        # A widget list to create a widget row.
        # Format:
        # - Widget type,
        # - widget object,
        # - column

        firstRowWidgetList = [('PM_ComboBox', self.currentLayerComboBox, 1),
                              ('PM_PushButton', self.addLayerButton, 2)]

        widgetRow = PM_WidgetRow(
            inPmGroupBox,
            title='',
            widgetList=firstRowWidgetList,
            label="Layer:",
            labelColumn=0,
        )

        self.layerCellsSpinBox = \
             PM_SpinBox( inPmGroupBox,
                        label         =  "Lattice cells:",
                        labelColumn   =  0,
                        value         =  2,
                        minimum       =  1,
                        maximum       =  25
                      )

        self.layerThicknessLineEdit = PM_LineEdit(inPmGroupBox,
                                                  label="Thickness:",
                                                  text="",
                                                  setAsDefault=False,
                                                  spanWidth=False)

        #self.layerThicknessLineEdit.setReadOnly(True)
        self.layerThicknessLineEdit.setDisabled(True)
        tooltip = "Thickness of layer in Angstroms"
        self.layerThicknessLineEdit.setToolTip(tooltip)
Пример #12
0
 def set_dimensions(self):
     width, height = 120, 160
     self.cover_size = QSize(width, height)
     f = self.parent().font()
     sz = f.pixelSize()
     if sz < 5:
         sz = f.pointSize() * self.parent().logicalDpiY() / 72.0
     self.title_height = max(25, sz + 10)
     self.item_size = self.cover_size + QSize(
         2 * self.MARGIN, (2 * self.MARGIN) + self.title_height)
     self.calculate_spacing()
Пример #13
0
 def update_tooltip(self, current_path):
     try:
         sz = self.pixmap.size()
     except:
         sz = QSize(0, 0)
     self.setToolTip(
         '<p>'+_('Double-click to open Book Details window') +
         '<br><br>' + _('Path') + ': ' + current_path +
         '<br><br>' + _('Cover size: %(width)d x %(height)d')%dict(
             width=sz.width(), height=sz.height())
     )
Пример #14
0
 def do_layout(self):
     if self.rect().width() == 0 or self.rect().height() == 0:
         return
     pixmap = self.pixmap
     pwidth, pheight = pixmap.width(), pixmap.height()
     try:
         self.pwidth, self.pheight = fit_image(pwidth, pheight,
                         self.rect().width(), self.rect().height())[1:]
     except:
         self.pwidth, self.pheight = self.rect().width()-1, \
                 self.rect().height()-1
     self.current_pixmap_size = QSize(self.pwidth, self.pheight)
     self.animation.setEndValue(self.current_pixmap_size)
Пример #15
0
    def __init__(self, parent, copy_fmt):
        QWidget.__init__(self, parent)
        self.dialog = parent
        self.copy_fmt = copy_fmt
        self.changed = False

        self.l = l = QGridLayout()
        self.setLayout(l)
        self.cover_from_format_button = QToolButton(self)
        self.cover_from_format_button.setToolTip(
            _('Set the cover for the book from the selected format'))
        self.cover_from_format_button.setIcon(QIcon(I('book.png')))
        self.cover_from_format_button.setIconSize(QSize(32, 32))

        self.metadata_from_format_button = QToolButton(self)
        self.metadata_from_format_button.setIcon(QIcon(I('edit_input.png')))
        self.metadata_from_format_button.setIconSize(QSize(32, 32))
        self.metadata_from_format_button.setToolTip(
            _('Set metadata for the book from the selected format'))

        self.add_format_button = QToolButton(self)
        self.add_format_button.setIcon(QIcon(I('add_book.png')))
        self.add_format_button.setIconSize(QSize(32, 32))
        self.add_format_button.clicked.connect(self.add_format)
        self.add_format_button.setToolTip(_('Add a format to this book'))

        self.remove_format_button = QToolButton(self)
        self.remove_format_button.setIcon(QIcon(I('trash.png')))
        self.remove_format_button.setIconSize(QSize(32, 32))
        self.remove_format_button.clicked.connect(self.remove_format)
        self.remove_format_button.setToolTip(
            _('Remove the selected format from this book'))

        self.formats = FormatList(self)
        self.formats.setAcceptDrops(True)
        self.formats.formats_dropped.connect(self.formats_dropped)
        self.formats.restore_fmt.connect(self.restore_fmt)
        self.formats.delete_format.connect(self.remove_format)
        self.formats.itemDoubleClicked.connect(self.show_format)
        self.formats.setDragDropMode(self.formats.DropOnly)
        self.formats.setIconSize(QSize(32, 32))
        self.formats.setMaximumWidth(200)

        l.addWidget(self.cover_from_format_button, 0, 0, 1, 1)
        l.addWidget(self.metadata_from_format_button, 2, 0, 1, 1)
        l.addWidget(self.add_format_button, 0, 2, 1, 1)
        l.addWidget(self.remove_format_button, 2, 2, 1, 1)
        l.addWidget(self.formats, 0, 1, 3, 1)

        self.temp_files = []
Пример #16
0
 def update_tooltip(self, current_path):
     try:
         sz = self.pixmap.size()
     except:
         sz = QSize(0, 0)
     self.setToolTip(
         "<p>"
         + _("Double-click to open Book Details window")
         + "<br><br>"
         + _("Path")
         + ": "
         + current_path
         + "<br><br>"
         + _("Cover size: %(width)d x %(height)d") % dict(width=sz.width(), height=sz.height())
     )
Пример #17
0
    def __init__(self):
        QWidget.__init__(self, ctx.mainScreen)
        self.setObjectName("InformationWindow")
        self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        self.setFixedHeight(50)
        self.setMaximumWidth(800)
        self.setStyleSheet("""
            QFrame#frame { border: 1px solid rgba(255,255,255,30);
                           /*border-radius: 4px;*/
                           background-color: rgba(0,0,0,100);}

            QLabel { border:none;
                     color:#FFFFFF;}

            QProgressBar { border: 1px solid white;}

            QProgressBar::chunk { background-color: #F1610D;
                                  width: 0.5px;}
        """)

        self.gridlayout = QGridLayout(self)
        self.frame = QFrame(self)
        self.frame.setObjectName("frame")
        self.horizontalLayout = QHBoxLayout(self.frame)
        self.horizontalLayout.setContentsMargins(10, 0, 10, 0)

        # Spinner
        self.spinner = QLabel(self.frame)
        self.spinner.setMinimumSize(QSize(16, 16))
        self.spinner.setMaximumSize(QSize(16, 16))
        self.spinner.setIndent(6)
        self.movie = QMovie(':/images/working.mng')
        self.spinner.setMovie(self.movie)
        self.movie.start()
        self.horizontalLayout.addWidget(self.spinner)

        # Message
        self.label = QLabel(self.frame)
        self.label.setAlignment(Qt.AlignCenter)
        self.label.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        self.icon = QLabel(self.frame)
        self.icon.setFixedWidth(16)
        self.icon.setFixedHeight(16)
        self.horizontalLayout.setSpacing(10)
        self.horizontalLayout.addWidget(self.icon)
        self.horizontalLayout.addWidget(self.label)

        self.gridlayout.addWidget(self.frame, 0, 0, 1, 1)
Пример #18
0
    def __init__(self, parent, column_type, profile, verbose=True):
        QDialog.__init__(self, parent.gui)
        self.column_type = column_type
        self.db = parent.gui.current_db
        self.gui = parent.gui
        self.modified_column = None
        self.previous_name = None
        self.profile = profile

        self.setupUi(self)
        self.verbose = verbose
        self._log_location()

        # Populate the icon
        self.icon.setText('')
        self.icon.setMaximumSize(QSize(40, 40))
        self.icon.setScaledContents(True)
        self.icon.setPixmap(QPixmap(I('wizard.png')))

        # Add the Accept button
        self.accept_button = self.bb.addButton('Button',
                                               QDialogButtonBox.AcceptRole)
        self.accept_button.setDefault(True)

        # Hook the QLineEdit box
        self.calibre_destination_le.textChanged.connect(
            self.validate_destination)

        self.populate_editor()

        self.highlight_step(1)

        # Hook the button events
        self.bb.clicked.connect(self.dispatch_button_click)
Пример #19
0
    def __init__(self, parent=None, name=None, modal=1, fl=0):
        #QDialog.__init__(self,parent,name,modal,fl)
        QDialog.__init__(self, parent)
        self.setModal(modal)
        qt4todo("handle flags in TextMessageBox.__init__")

        if name is None: name = "TextMessageBox"
        self.setObjectName(name)
        self.setWindowTitle(name)

        TextMessageLayout = QVBoxLayout(self)
        TextMessageLayout.setMargin(5)
        TextMessageLayout.setSpacing(1)

        self.text_edit = QTextEdit(self)

        TextMessageLayout.addWidget(self.text_edit)

        self.close_button = QPushButton(self)
        self.close_button.setText("Close")
        TextMessageLayout.addWidget(self.close_button)

        self.resize(QSize(350, 300).expandedTo(self.minimumSizeHint()))
        # Width changed from 300 to 350. Now hscrollbar doesn't appear in
        # Help > Graphics Info textbox. mark 060322
        qt4todo('self.clearWState(Qt.WState_Polished)')  # what is this?

        self.connect(self.close_button, SIGNAL("clicked()"), self.close)
Пример #20
0
 def __init__(self, parent=None):
     QWidget.__init__(self, parent)
     self._pixmap = QPixmap(self)
     self.setMinimumSize(QSize(150, 200))
     ImageDropMixin.__init__(self)
     self.draw_border = True
     self.show_size = False
Пример #21
0
 def set_normal_icon_size(self, w, h):
     self.normal_icon_size = QSize(w, h)
     self.setIconSize(self.normal_icon_size)
     try:
         self.setMinimumSize(self.sizeHint())
     except:
         self.setMinimumSize(QSize(w+5, h+5))
Пример #22
0
    def createActions(self):
        self.nameLabel = QLabel(self.mobile.name)
        self.nameLabel.setMinimumSize(80, 23)
        self.nameLabelAction = QWidgetAction(self)
        self.nameLabelAction.setDefaultWidget(self.nameLabel)
        self.addAction(self.nameLabelAction)

        self.enableAction = QAction("Enable Display", self)
        self.enableAction.setCheckable(True)
        self.enableAction.setChecked(True)
        icon = QIcon(':/plugins/PosiView/ledgrey.png')
        icon.addFile(':/plugins/PosiView/ledgreen.png', QSize(), QIcon.Normal,
                     QIcon.On)
        self.enableAction.setIcon(icon)
        self.addAction(self.enableAction)
        self.enableAction.triggered.connect(self.onEnableClicked)
        self.enableAction.triggered.connect(self.mobile.setEnabled)

        self.addSeparator()
        self.posLabel = QLabel("--:--:-- 0.000000 0.000000\nd = 0.0")
        self.posLabel.setAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
        self.posLabel.setMinimumSize(180, 23)
        self.posLabel.setStyleSheet('background: red; font-size: 8pt')
        self.posLabelAction = QWidgetAction(self)
        self.posLabelAction.setDefaultWidget(self.posLabel)
        self.addAction(self.posLabelAction)
        self.centerAction = QAction(QIcon(':/plugins/PosiView/center.png'),
                                    "Center &Map", self)
        self.addAction(self.centerAction)
        self.deleteTrackAction = QAction(
            QIcon(':/plugins/PosiView/deletetrack.png'), 'Delete &Track', self)
        self.addAction(self.deleteTrackAction)
        self.deleteTrackAction.triggered.connect(self.mobile.deleteTrack)
        self.centerAction.triggered.connect(self.mobile.centerOnMap)
Пример #23
0
    def __init__(self, process, calculation):
        """
        """
        QDialog.__init__(self, None, None, True)

        self.process = process

        self.setCaption("Please Wait")

        pbVBLayout = QVBoxLayout(self, 11, 6, "ProgressBarDialogLayout")

        msgLabel = QLabel(self, "msgLabel")
        msgLabel.setAlignment(QLabel.AlignCenter)

        if calculation == 'Energy':
            msgLabel.setText("Calculating Energy ...")
        else:
            msgLabel.setText("Optimizing ...")

        pbVBLayout.addWidget(msgLabel)

        self.msgLabel2 = QLabel(self, "msgLabel2")
        self.msgLabel2.setAlignment(QLabel.AlignCenter)
        self.msgLabel2.setText('')

        pbVBLayout.addWidget(self.msgLabel2)

        cancelButton = QPushButton(self, "canel")
        cancelButton.setText("Cancel")

        pbVBLayout.addWidget(cancelButton)

        self.resize(QSize(248, 146).expandedTo(self.minimumSizeHint()))
        self.connect(cancelButton, SIGNAL("clicked()"), self.reject)
        return
Пример #24
0
    def activateBondsTool(self):
        """
        Activate the bond tool of the Build Atoms mode 
        Show only the Bond Tools groupbox in the Build Atoms Property manager
        and hide the others.
        @see:self._convert_bonds_bet_selected_atoms()
        """
        self._currentActiveTool = 'BONDS_TOOL'

        for widget in (self.propMgr.previewGroupBox,
                       self.propMgr.elementChooser,
                       self.propMgr.atomChooserComboBox):
            widget.hide()

        self.propMgr.bondToolsGroupBox.show()

        self.propMgr.pw.propertyManagerScrollArea.ensureWidgetVisible(
            self.propMgr.headerFrame)

        #note: its okay if the check_action is None
        checked_action = self.flyoutToolbar.getCheckedBondToolAction()
        self.changeBondTool(action=checked_action)

        bondToolActions = self.flyoutToolbar.getBondToolActions()
        for btn in self.propMgr.bondToolButtonRow.buttonGroup.buttons():
            btnId = self.propMgr.bondToolButtonRow.buttonGroup.id(btn)
            action = bondToolActions[btnId]
            btn.setIconSize(QSize(24, 24))
            btn.setDefaultAction(action)

        self.win.win_update()
Пример #25
0
    def __init__(self, parent=None, name=None, modal=0, fl=None):
        if fl is None:
            fl = Qt.Dialog | Qt.WindowTitleHint
        QDialog.__init__(self, parent, Qt.Dialog | Qt.WindowTitleHint)
        self.setModal(modal)

        image0 = pixmaps.tigger_logo.pm()

        # self.setSizeGripEnabled(0)
        LayoutWidget = QWidget(self)
        LayoutWidget.setSizePolicy(QSizePolicy.MinimumExpanding,
                                   QSizePolicy.MinimumExpanding)

        lo_top = QVBoxLayout(LayoutWidget)

        lo_title = QHBoxLayout(None)

        self.title_icon = QLabel(LayoutWidget)
        self.title_icon.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        self.title_icon.setPixmap(image0)
        self.title_icon.setAlignment(Qt.AlignCenter)
        lo_title.addWidget(self.title_icon)

        self.title_label = QLabel(LayoutWidget)
        self.title_label.setWordWrap(True)
        lo_title.addWidget(self.title_label)
        lo_top.addLayout(lo_title)

        lo_logos = QHBoxLayout(None)
        lo_top.addLayout(lo_logos)
        # for logo in ("astron",):
        #   icon = QLabel(LayoutWidget)
        #   icon.setSizePolicy(QSizePolicy.Fixed,QSizePolicy.Fixed)
        #   icon.setPixmap(getattr(pixmaps,logo+"_logo").pm())
        #   icon.setAlignment(Qt.AlignCenter)
        #   lo_logos.addWidget(icon)

        lo_mainbtn = QHBoxLayout(None)
        lo_mainbtn.addItem(
            QSpacerItem(20, 20, QSizePolicy.Expanding, QSizePolicy.Minimum))
        lo_top.addLayout(lo_mainbtn)

        self.btn_ok = QPushButton(LayoutWidget)
        self.btn_ok.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        self.btn_ok.setMinimumSize(QSize(60, 0))
        self.btn_ok.setAutoDefault(1)
        self.btn_ok.setDefault(1)
        lo_mainbtn.addWidget(self.btn_ok)
        lo_mainbtn.addItem(
            QSpacerItem(20, 20, QSizePolicy.Expanding, QSizePolicy.Minimum))

        self.languageChange()

        LayoutWidget.adjustSize()

        # LayoutWidget.resize(QSize(489,330).expandedTo(LayoutWidget.minimumSizeHint()))
        # self.resize(QSize(489,330).expandedTo(self.minimumSizeHint()))
        # self.clearWState(Qt.WState_Polished)

        self.connect(self.btn_ok, SIGNAL("clicked()"), self.accept)
Пример #26
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()
Пример #27
0
def render_html(path_to_html, width=590, height=750, as_xhtml=True):
    from PyQt4.QtWebKit import QWebPage
    from PyQt4.Qt import QEventLoop, QPalette, Qt, QUrl, QSize
    from calibre.gui2 import is_ok_to_use_qt
    if not is_ok_to_use_qt():
        return None
    path_to_html = os.path.abspath(path_to_html)
    with CurrentDir(os.path.dirname(path_to_html)):
        page = QWebPage()
        pal = page.palette()
        pal.setBrush(QPalette.Background, Qt.white)
        page.setPalette(pal)
        page.setViewportSize(QSize(width, height))
        page.mainFrame().setScrollBarPolicy(Qt.Vertical, Qt.ScrollBarAlwaysOff)
        page.mainFrame().setScrollBarPolicy(Qt.Horizontal, Qt.ScrollBarAlwaysOff)
        loop = QEventLoop()
        renderer = HTMLRenderer(page, loop)
        page.loadFinished.connect(renderer, type=Qt.QueuedConnection)
        if as_xhtml:
            page.mainFrame().setContent(open(path_to_html, 'rb').read(),
                    'application/xhtml+xml', QUrl.fromLocalFile(path_to_html))
        else:
            page.mainFrame().load(QUrl.fromLocalFile(path_to_html))
        loop.exec_()
    renderer.loop = renderer.page = None
    page.loadFinished.disconnect()
    del page
    del loop
    if isinstance(renderer.exception, ParserError) and as_xhtml:
        return render_html(path_to_html, width=width, height=height,
                as_xhtml=False)
    return renderer
Пример #28
0
    def __init__(self, log, parent=None):
        QDialog.__init__(self, parent)
        self.log = log
        self.l = l = QVBoxLayout()
        self.setLayout(l)

        self.tb = QTextBrowser(self)
        l.addWidget(self.tb)

        self.bb = QDialogButtonBox(QDialogButtonBox.Close)
        l.addWidget(self.bb)
        self.copy_button = self.bb.addButton(_('Copy to clipboard'),
                                             self.bb.ActionRole)
        self.copy_button.clicked.connect(self.copy_to_clipboard)
        self.copy_button.setIcon(QIcon(I('edit-copy.png')))
        self.bb.rejected.connect(self.reject)
        self.bb.accepted.connect(self.accept)

        self.setWindowTitle(_('Download log'))
        self.setWindowIcon(QIcon(I('debug.png')))
        self.resize(QSize(800, 400))

        self.keep_updating = True
        self.last_html = None
        self.finished.connect(self.stop)
        QTimer.singleShot(100, self.update_log)

        self.show()
Пример #29
0
    def __init__(self, names, parent=None):
        QDialog.__init__(self, parent)
        self.setWindowTitle(_('Choose master file'))
        self.l = l = QVBoxLayout()
        self.setLayout(l)
        self.la = la = QLabel(
            _('Choose the master file. All selected files will be merged into the master file:'
              ))
        la.setWordWrap(True)
        l.addWidget(la)
        self.sa = sa = QScrollArea(self)
        l.addWidget(sa)
        self.bb = bb = QDialogButtonBox(QDialogButtonBox.Ok
                                        | QDialogButtonBox.Cancel)
        l.addWidget(bb)
        bb.accepted.connect(self.accept)
        bb.rejected.connect(self.reject)
        self.w = w = QWidget(self)
        w.l = QVBoxLayout()
        w.setLayout(w.l)

        buttons = self.buttons = [QRadioButton(n) for n in names]
        buttons[0].setChecked(True)
        map(w.l.addWidget, buttons)
        sa.setWidget(w)

        self.resize(self.sizeHint() + QSize(150, 20))
Пример #30
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)
Пример #31
0
 def filename_button_clicked(self):
     try:
         path = choose_files(self, 'choose_category_icon',
                     _('Select Icon'), filters=[
                     ('Images', ['png', 'gif', 'jpg', 'jpeg'])],
                 all_files=False, select_only_single_file=True)
         if path:
             icon_path = path[0]
             icon_name = sanitize_file_name_unicode(
                          os.path.splitext(
                                os.path.basename(icon_path))[0]+'.png')
             if icon_name not in self.icon_file_names:
                 self.icon_file_names.append(icon_name)
                 self.update_filename_box()
                 try:
                     p = QIcon(icon_path).pixmap(QSize(128, 128))
                     d = os.path.join(config_dir, 'cc_icons')
                     if not os.path.exists(os.path.join(d, icon_name)):
                         if not os.path.exists(d):
                             os.makedirs(d)
                         with open(os.path.join(d, icon_name), 'wb') as f:
                             f.write(pixmap_to_data(p, format='PNG'))
                 except:
                     traceback.print_exc()
             self.icon_files.setCurrentIndex(self.icon_files.findText(icon_name))
             self.icon_files.adjustSize()
     except:
         traceback.print_exc()
     return
Пример #32
0
    def __init__(self, stats, location, parent=None):
        QDialog.__init__(self, parent)
        self.setWindowTitle(_('No library found'))
        self._l = l = QGridLayout(self)
        self.setLayout(l)
        self.stats, self.location = stats, location

        loc = self.oldloc = location.replace('/', os.sep)
        self.header = QLabel(
            _('No existing calibre library was found at %s. '
              'If the library was moved, select its new location below. '
              'Otherwise calibre will forget this library.') % loc)
        self.header.setWordWrap(True)
        ncols = 2
        l.addWidget(self.header, 0, 0, 1, ncols)
        self.cl = QLabel('<br><b>' + _('New location of this library:'))
        l.addWidget(self.cl, 1, 0, 1, ncols)
        self.loc = QLineEdit(loc, self)
        l.addWidget(self.loc, 2, 0, 1, 1)
        self.cd = QToolButton(self)
        self.cd.setIcon(QIcon(I('document_open.png')))
        self.cd.clicked.connect(self.choose_dir)
        l.addWidget(self.cd, 2, 1, 1, 1)
        self.bb = QDialogButtonBox(QDialogButtonBox.Abort)
        b = self.bb.addButton(_('Library moved'), self.bb.AcceptRole)
        b.setIcon(QIcon(I('ok.png')))
        b = self.bb.addButton(_('Forget library'), self.bb.RejectRole)
        b.setIcon(QIcon(I('edit-clear.png')))
        b.clicked.connect(self.forget_library)
        self.bb.accepted.connect(self.accept)
        self.bb.rejected.connect(self.reject)
        l.addWidget(self.bb, 3, 0, 1, ncols)
        self.resize(self.sizeHint() + QSize(100, 50))
Пример #33
0
 def render_html(self, ok):
     try:
         if not ok:
             return
         cwidth, cheight = self.page.mainFrame().contentsSize().width(
         ), self.page.mainFrame().contentsSize().height()
         self.page.setViewportSize(QSize(cwidth, cheight))
         factor = float(self.width) / cwidth if cwidth > self.width else 1
         cutoff_height = int(self.height / factor) - 3
         image = QImage(self.page.viewportSize(), QImage.Format_ARGB32)
         image.setDotsPerMeterX(self.dpi * (100 / 2.54))
         image.setDotsPerMeterY(self.dpi * (100 / 2.54))
         painter = QPainter(image)
         self.page.mainFrame().render(painter)
         painter.end()
         cheight = image.height()
         cwidth = image.width()
         pos = 0
         while pos < cheight:
             img = image.copy(0, pos, cwidth,
                              min(cheight - pos, cutoff_height))
             pos += cutoff_height - 20
             if cwidth > self.width:
                 img = img.scaledToWidth(self.width, Qt.SmoothTransform)
             f = os.path.join(self.tdir, '%d.png' % pos)
             img.save(f)
             self.images.append((f, img.width(), img.height()))
     finally:
         QApplication.quit()
Пример #34
0
 def __init__(self, *args):
     QToolButton.__init__(self, *args)
     self.animation = QPropertyAnimation(self, 'iconSize', self)
     self.animation.setDuration(60/72.*1000)
     self.animation.setLoopCount(4)
     self.normal_icon_size = QSize(64, 64)
     self.animation.valueChanged.connect(self.value_changed)
     self.setCursor(Qt.PointingHandCursor)
     self.animation.finished.connect(self.animation_finished)
Пример #35
0
 def set_dimensions(self):
     width, height = 120, 160
     self.cover_size = QSize(width, height)
     f = self.parent().font()
     sz = f.pixelSize()
     if sz < 5:
         sz = f.pointSize() * self.parent().logicalDpiY() / 72.0
     self.title_height = max(25, sz + 10)
     self.item_size = self.cover_size + QSize(2 * self.MARGIN, (2 * self.MARGIN) + self.title_height)
     self.calculate_spacing()
Пример #36
0
 def do_layout(self):
     if self.rect().width() == 0 or self.rect().height() == 0:
         return
     pixmap = self.pixmap
     pwidth, pheight = pixmap.width(), pixmap.height()
     try:
         self.pwidth, self.pheight = fit_image(pwidth, pheight, self.rect().width(), self.rect().height())[1:]
     except:
         self.pwidth, self.pheight = self.rect().width() - 1, self.rect().height() - 1
     self.current_pixmap_size = QSize(self.pwidth, self.pheight)
     self.animation.setEndValue(self.current_pixmap_size)
Пример #37
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.)
        height = self.current_pixmap_size.height()
        extray = canvas_size.height() - height
        if extray < 0:
            extray = 0
        y = int(extray/2.)
        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)
Пример #38
0
class ThrobbingButton(QToolButton):

    def __init__(self, *args):
        QToolButton.__init__(self, *args)
        self.animation = QPropertyAnimation(self, 'iconSize', self)
        self.animation.setDuration(60/72.*1000)
        self.animation.setLoopCount(4)
        self.normal_icon_size = QSize(64, 64)
        self.animation.valueChanged.connect(self.value_changed)
        self.setCursor(Qt.PointingHandCursor)
        self.animation.finished.connect(self.animation_finished)

    def set_normal_icon_size(self, w, h):
        self.normal_icon_size = QSize(w, h)
        self.setIconSize(self.normal_icon_size)
        try:
            self.setMinimumSize(self.sizeHint())
        except:
            self.setMinimumSize(QSize(w+5, h+5))

    def animation_finished(self):
        self.setIconSize(self.normal_icon_size)

    def enterEvent(self, ev):
        self.start_animation()

    def leaveEvent(self, ev):
        self.stop_animation()

    def value_changed(self, val):
        self.update()

    def start_animation(self):
        if config['disable_animations']:
            return
        if self.animation.state() != self.animation.Stopped or not self.isVisible():
            return
        size = self.normal_icon_size.width()
        smaller = int(0.7 * size)
        self.animation.setStartValue(QSize(smaller, smaller))
        self.animation.setEndValue(self.normal_icon_size)
        QMetaObject.invokeMethod(self.animation, 'start', Qt.QueuedConnection)

    def stop_animation(self):
        self.animation.stop()
        self.animation_finished()
Пример #39
0
class CoverView(QWidget):  # {{{

    cover_changed = pyqtSignal(object, object)
    cover_removed = pyqtSignal(object)

    def __init__(self, vertical, parent=None):
        QWidget.__init__(self, parent)
        self._current_pixmap_size = QSize(120, 120)
        self.vertical = vertical

        self.animation = QPropertyAnimation(self, '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('book.png'))
        self.pixmap = self.default_pixmap
        self.pwidth = self.pheight = None
        self.data = {}

        self.do_layout()

    def value_changed(self, val):
        self.update()

    def setCurrentPixmapSize(self, val):
        self._current_pixmap_size = val

    def do_layout(self):
        if self.rect().width() == 0 or self.rect().height() == 0:
            return
        pixmap = self.pixmap
        pwidth, pheight = pixmap.width(), pixmap.height()
        try:
            self.pwidth, self.pheight = fit_image(pwidth, pheight,
                            self.rect().width(), self.rect().height())[1:]
        except:
            self.pwidth, self.pheight = self.rect().width()-1, \
                    self.rect().height()-1
        self.current_pixmap_size = QSize(self.pwidth, self.pheight)
        self.animation.setEndValue(self.current_pixmap_size)

    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()

    def paintEvent(self, event):
        canvas_size = self.rect()
        width = self.current_pixmap_size.width()
        extrax = canvas_size.width() - width
        if extrax < 0:
            extrax = 0
        x = int(extrax/2.)
        height = self.current_pixmap_size.height()
        extray = canvas_size.height() - height
        if extray < 0:
            extray = 0
        y = int(extray/2.)
        target = QRect(x, y, width, height)
        p = QPainter(self)
        p.setRenderHints(QPainter.Antialiasing | QPainter.SmoothPixmapTransform)
        p.drawPixmap(target, self.pixmap.scaled(target.size(),
            Qt.KeepAspectRatio, Qt.SmoothTransformation))
        if gprefs['bd_overlay_cover_size']:
            sztgt = target.adjusted(0, 0, 0, -4)
            f = p.font()
            f.setBold(True)
            p.setFont(f)
            sz = u'\u00a0%d x %d\u00a0'%(self.pixmap.width(), self.pixmap.height())
            flags = Qt.AlignBottom|Qt.AlignRight|Qt.TextSingleLine
            szrect = p.boundingRect(sztgt, flags, sz)
            p.fillRect(szrect.adjusted(0, 0, 0, 4), QColor(0, 0, 0, 200))
            p.setPen(QPen(QColor(255,255,255)))
            p.drawText(sztgt, flags, sz)
        p.end()

    current_pixmap_size = pyqtProperty('QSize',
            fget=lambda self: self._current_pixmap_size,
            fset=setCurrentPixmapSize
            )

    def contextMenuEvent(self, ev):
        cm = QMenu(self)
        paste = cm.addAction(_('Paste Cover'))
        copy = cm.addAction(_('Copy Cover'))
        remove = cm.addAction(_('Remove Cover'))
        if not QApplication.instance().clipboard().mimeData().hasImage():
            paste.setEnabled(False)
        copy.triggered.connect(self.copy_to_clipboard)
        paste.triggered.connect(self.paste_from_clipboard)
        remove.triggered.connect(self.remove_cover)
        cm.exec_(ev.globalPos())

    def copy_to_clipboard(self):
        QApplication.instance().clipboard().setPixmap(self.pixmap)

    def paste_from_clipboard(self, pmap=None):
        if not isinstance(pmap, QPixmap):
            cb = QApplication.instance().clipboard()
            pmap = cb.pixmap()
            if pmap.isNull() and cb.supportsSelection():
                pmap = cb.pixmap(cb.Selection)
        if not pmap.isNull():
            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_,
                    pixmap_to_data(pmap))

    def remove_cover(self):
        id_ = self.data.get('id', None)
        self.pixmap = self.default_pixmap
        self.do_layout()
        self.update()
        if id_ is not None:
            self.cover_removed.emit(id_)

    def update_tooltip(self, current_path):
        try:
            sz = self.pixmap.size()
        except:
            sz = QSize(0, 0)
        self.setToolTip(
            '<p>'+_('Double-click to open Book Details window') +
            '<br><br>' + _('Path') + ': ' + current_path +
            '<br><br>' + _('Cover size: %(width)d x %(height)d')%dict(
                width=sz.width(), height=sz.height())
        )
Пример #40
0
 def sizeHint(self):
     size = QSize()
     size.setWidth(1000)
     return size
Пример #41
0
class ImageDelegate(QStyledItemDelegate):

    MARGIN = 4

    def __init__(self, parent):
        super(ImageDelegate, self).__init__(parent)
        self.set_dimensions()
        self.cover_cache = {}

    def set_dimensions(self):
        width, height = 120, 160
        self.cover_size = QSize(width, height)
        f = self.parent().font()
        sz = f.pixelSize()
        if sz < 5:
            sz = f.pointSize() * self.parent().logicalDpiY() / 72.0
        self.title_height = max(25, sz + 10)
        self.item_size = self.cover_size + QSize(2 * self.MARGIN, (2 * self.MARGIN) + self.title_height)
        self.calculate_spacing()

    def calculate_spacing(self):
        self.spacing = max(10, min(50, int(0.1 * self.item_size.width())))

    def sizeHint(self, option, index):
        return self.item_size

    def paint(self, painter, option, index):
        QStyledItemDelegate.paint(self, painter, option, QModelIndex())  # draw the hover and selection highlights
        name = unicode(index.data(Qt.DisplayRole).toString())
        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()
Пример #42
0
 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)