def process_duplicates(self, db, duplicates): ta = _('%(title)s by %(author)s') bf = QFont(self.dup_list.font()) bf.setBold(True) itf = QFont(self.dup_list.font()) itf.setItalic(True) for mi, cover, formats in duplicates: item = QTreeWidgetItem([ta%dict( title=mi.title, author=mi.format_field('authors')[1])] , 0) item.setCheckState(0, Qt.Checked) item.setFlags(Qt.ItemIsEnabled|Qt.ItemIsUserCheckable) item.setData(0, Qt.FontRole, bf) item.setData(0, Qt.UserRole, (mi, cover, formats)) matching_books = db.books_with_same_title(mi) def add_child(text): c = QTreeWidgetItem([text], 1) c.setFlags(Qt.ItemIsEnabled) item.addChild(c) return c add_child(_('Already in calibre:')).setData(0, Qt.FontRole, itf) for book_id in matching_books: aut = [a.replace('|', ',') for a in (db.authors(book_id, index_is_id=True) or '').split(',')] add_child(ta%dict( title=db.title(book_id, index_is_id=True), author=authors_to_string(aut))) add_child('') yield item
class HeaderView(QHeaderView): # {{{ def __init__(self, *args): QHeaderView.__init__(self, *args) self.hover = -1 self.current_font = QFont(self.font()) self.current_font.setBold(True) self.current_font.setItalic(True) def event(self, e): if e.type() in (e.HoverMove, e.HoverEnter): self.hover = self.logicalIndexAt(e.pos()) elif e.type() in (e.Leave, e.HoverLeave): self.hover = -1 return QHeaderView.event(self, e) def paintSection(self, painter, rect, logical_index): opt = QStyleOptionHeader() self.initStyleOption(opt) opt.rect = rect opt.section = logical_index opt.orientation = self.orientation() opt.textAlignment = Qt.AlignHCenter | Qt.AlignVCenter model = self.parent().model() opt.text = model.headerData(logical_index, opt.orientation, Qt.DisplayRole).toString() if self.isSortIndicatorShown() and self.sortIndicatorSection( ) == logical_index: opt.sortIndicator = QStyleOptionHeader.SortDown if self.sortIndicatorOrder( ) == Qt.AscendingOrder else QStyleOptionHeader.SortUp opt.text = opt.fontMetrics.elidedText(opt.text, Qt.ElideRight, rect.width() - 4) if self.isEnabled(): opt.state |= QStyle.State_Enabled if self.window().isActiveWindow(): opt.state |= QStyle.State_Active if self.hover == logical_index: opt.state |= QStyle.State_MouseOver sm = self.selectionModel() if opt.orientation == Qt.Vertical: try: opt.icon = model.headerData(logical_index, opt.orientation, Qt.DecorationRole) opt.iconAlignment = Qt.AlignVCenter except (IndexError, ValueError, TypeError): pass if sm.isRowSelected(logical_index, QModelIndex()): opt.state |= QStyle.State_Sunken painter.save() if ((opt.orientation == Qt.Horizontal and sm.currentIndex().column() == logical_index) or (opt.orientation == Qt.Vertical and sm.currentIndex().row() == logical_index)): painter.setFont(self.current_font) self.style().drawControl(QStyle.CE_Header, opt, painter, self) painter.restore()
def set_window_title(self): db = self.current_db restrictions = [x for x in (db.data.get_base_restriction_name(), db.data.get_search_restriction_name()) if x] restrictions = " :: ".join(restrictions) font = QFont() if restrictions: restrictions = " :: " + restrictions font.setBold(True) font.setItalic(True) self.virtual_library.setFont(font) title = u"{0} - || {1}{2} ||".format(__appname__, self.iactions["Choose Library"].library_name(), restrictions) self.setWindowTitle(title)
def set_favorite(self): item = self.dictionaries.currentItem() bf = QFont(self.dictionaries.font()) bf.setItalic(True) for x in (item.parent().child(i) for i in xrange(item.parent().childCount())): x.setData(0, Qt.FontRole, bf if x is item else None) cc = unicode(item.parent().data(0, Qt.UserRole).toPyObject()) lc = unicode(item.parent().parent().data(0, Qt.UserRole).toPyObject()) d = item.data(0, Qt.UserRole).toPyObject() locale = '%s-%s' % (lc, cc) pl = dprefs['preferred_dictionaries'] pl[locale] = d.id dprefs['preferred_dictionaries'] = pl
class HeaderView(QHeaderView): # {{{ def __init__(self, *args): QHeaderView.__init__(self, *args) self.hover = -1 self.current_font = QFont(self.font()) self.current_font.setBold(True) self.current_font.setItalic(True) def event(self, e): if e.type() in (e.HoverMove, e.HoverEnter): self.hover = self.logicalIndexAt(e.pos()) elif e.type() in (e.Leave, e.HoverLeave): self.hover = -1 return QHeaderView.event(self, e) def paintSection(self, painter, rect, logical_index): opt = QStyleOptionHeader() self.initStyleOption(opt) opt.rect = rect opt.section = logical_index opt.orientation = self.orientation() opt.textAlignment = Qt.AlignHCenter | Qt.AlignVCenter model = self.parent().model() opt.text = model.headerData(logical_index, opt.orientation, Qt.DisplayRole).toString() if self.isSortIndicatorShown() and self.sortIndicatorSection() == logical_index: opt.sortIndicator = QStyleOptionHeader.SortDown if self.sortIndicatorOrder() == Qt.AscendingOrder else QStyleOptionHeader.SortUp opt.text = opt.fontMetrics.elidedText(opt.text, Qt.ElideRight, rect.width() - 4) if self.isEnabled(): opt.state |= QStyle.State_Enabled if self.window().isActiveWindow(): opt.state |= QStyle.State_Active if self.hover == logical_index: opt.state |= QStyle.State_MouseOver sm = self.selectionModel() if opt.orientation == Qt.Vertical: try: opt.icon = model.headerData(logical_index, opt.orientation, Qt.DecorationRole) opt.iconAlignment = Qt.AlignVCenter except TypeError: pass if sm.isRowSelected(logical_index, QModelIndex()): opt.state |= QStyle.State_Sunken painter.save() if ( (opt.orientation == Qt.Horizontal and sm.currentIndex().column() == logical_index) or (opt.orientation == Qt.Vertical and sm.currentIndex().row() == logical_index)): painter.setFont(self.current_font) self.style().drawControl(QStyle.CE_Header, opt, painter, self) painter.restore()
def set_window_title(self): db = self.current_db restrictions = [x for x in (db.data.get_base_restriction_name(), db.data.get_search_restriction_name()) if x] restrictions = ' :: '.join(restrictions) font = QFont() if restrictions: restrictions = ' :: ' + restrictions font.setBold(True) font.setItalic(True) self.virtual_library.setFont(font) title = u'{0} - || {1}{2} ||'.format( __appname__, self.iactions['Choose Library'].library_name(), restrictions) self.setWindowTitle(title)
def process_duplicates(self, db, duplicates): ta = _('%(title)s by %(author)s [%(formats)s]') bf = QFont(self.dup_list.font()) bf.setBold(True) itf = QFont(self.dup_list.font()) itf.setItalic(True) for mi, cover, formats in duplicates: # formats is a list of file paths # Grab just the extension and display to the user # Based only off the file name, no file type tests are done. incoming_formats = ', '.join( os.path.splitext(path)[-1].replace('.', '').upper() for path in formats) item = QTreeWidgetItem([ ta % dict(title=mi.title, author=mi.format_field('authors')[1], formats=incoming_formats) ], 0) item.setCheckState(0, Qt.Checked) item.setFlags(Qt.ItemIsEnabled | Qt.ItemIsUserCheckable) item.setData(0, Qt.FontRole, bf) item.setData(0, Qt.UserRole, (mi, cover, formats)) matching_books = db.books_with_same_title(mi) def add_child(text): c = QTreeWidgetItem([text], 1) c.setFlags(Qt.ItemIsEnabled) item.addChild(c) return c add_child(_('Already in calibre:')).setData(0, Qt.FontRole, itf) for book_id in matching_books: aut = [ a.replace('|', ',') for a in ( db.authors(book_id, index_is_id=True) or '').split(',') ] add_child( ta % dict(title=db.title(book_id, index_is_id=True), author=authors_to_string(aut), formats=db.formats( book_id, index_is_id=True, verify_formats=False))) add_child('') yield item
def paintEvent(self, ev): # We do it like this so that the popup uses a normal font if self.emphasize: ofont = self.font() f = QFont(ofont) f.setBold(True), f.setItalic(True) self.setFont(f) QComboBox.paintEvent(self, ev) if self.emphasize: self.setFont(ofont)
def process_duplicates(self, db, duplicates): ta = _('%(title)s by %(author)s [%(formats)s]') bf = QFont(self.dup_list.font()) bf.setBold(True) itf = QFont(self.dup_list.font()) itf.setItalic(True) for mi, cover, formats in duplicates: # formats is a list of file paths # Grab just the extension and display to the user # Based only off the file name, no file type tests are done. incoming_formats = ', '.join(os.path.splitext(path)[-1].replace('.', '').upper() for path in formats) item = QTreeWidgetItem([ta%dict( title=mi.title, author=mi.format_field('authors')[1], formats=incoming_formats)] , 0) item.setCheckState(0, Qt.Checked) item.setFlags(Qt.ItemIsEnabled|Qt.ItemIsUserCheckable) item.setData(0, Qt.FontRole, bf) item.setData(0, Qt.UserRole, (mi, cover, formats)) matching_books = db.books_with_same_title(mi) def add_child(text): c = QTreeWidgetItem([text], 1) c.setFlags(Qt.ItemIsEnabled) item.addChild(c) return c add_child(_('Already in calibre:')).setData(0, Qt.FontRole, itf) for book_id in matching_books: aut = [a.replace('|', ',') for a in (db.authors(book_id, index_is_id=True) or '').split(',')] add_child(ta%dict( title=db.title(book_id, index_is_id=True), author=authors_to_string(aut), formats=db.formats(book_id, index_is_id=True, verify_formats=False))) add_child('') yield item
def build_dictionaries(self, reread=False): all_dictionaries = builtin_dictionaries() | custom_dictionaries(reread=reread) languages = defaultdict(lambda : defaultdict(set)) for d in all_dictionaries: for locale in d.locales | {d.primary_locale}: languages[locale.langcode][locale.countrycode].add(d) bf = QFont(self.dictionaries.font()) bf.setBold(True) itf = QFont(self.dictionaries.font()) itf.setItalic(True) self.dictionaries.clear() for lc in sorted(languages, key=lambda x:sort_key(calibre_langcode_to_name(x))): i = QTreeWidgetItem(self.dictionaries, LANG) i.setText(0, calibre_langcode_to_name(lc)) i.setData(0, Qt.UserRole, lc) best_country = getattr(best_locale_for_language(lc), 'countrycode', None) for countrycode in sorted(languages[lc], key=lambda x: country_map()['names'].get(x, x)): j = QTreeWidgetItem(i, COUNTRY) j.setText(0, country_map()['names'].get(countrycode, countrycode)) j.setData(0, Qt.UserRole, countrycode) if countrycode == best_country: j.setData(0, Qt.FontRole, bf) pd = get_dictionary(DictionaryLocale(lc, countrycode)) for dictionary in sorted(languages[lc][countrycode], key=lambda d:d.name): k = QTreeWidgetItem(j, DICTIONARY) pl = calibre_langcode_to_name(dictionary.primary_locale.langcode) if dictionary.primary_locale.countrycode: pl += '-' + dictionary.primary_locale.countrycode.upper() k.setText(0, dictionary.name or (_('<Builtin dictionary for {0}>').format(pl))) k.setData(0, Qt.UserRole, dictionary) if dictionary.name: k.setFlags(k.flags() | Qt.ItemIsEditable) if pd == dictionary: k.setData(0, Qt.FontRole, itf) self.dictionaries.expandAll()
def mark_item_as_current(self, item): font = QFont(self.font()) font.setItalic(True) font.setBold(True) item.setData(0, Qt.FontRole, font)
class CompareSingle(QWidget): def __init__(self, field_metadata, parent=None, revert_tooltip=None, datetime_fmt='MMMM yyyy', blank_as_equal=True, fields=('title', 'authors', 'series', 'tags', 'rating', 'publisher', 'pubdate', 'identifiers', 'languages', 'comments', 'cover')): QWidget.__init__(self, parent) self.l = l = QGridLayout() l.setContentsMargins(0, 0, 0, 0) self.setLayout(l) revert_tooltip = revert_tooltip or _('Revert %s') self.current_mi = None self.changed_font = QFont(QApplication.font()) self.changed_font.setBold(True) self.changed_font.setItalic(True) self.blank_as_equal = blank_as_equal self.widgets = OrderedDict() row = 0 for field in fields: m = field_metadata[field] dt = m['datatype'] extra = None if 'series' in {field, dt}: cls = SeriesEdit elif field == 'identifiers': cls = IdentifiersEdit elif field == 'languages': cls = LanguagesEdit elif 'comments' in {field, dt}: cls = CommentsEdit elif 'rating' in {field, dt}: cls = RatingsEdit elif dt == 'datetime': extra = datetime_fmt cls = DateEdit elif field == 'cover': cls = CoverView elif dt in {'text', 'enum'}: cls = LineEdit else: continue neww = cls(field, True, self, m, extra) neww.changed.connect(partial(self.changed, field)) oldw = cls(field, False, self, m, extra) newl = QLabel('&%s:' % m['name']) newl.setBuddy(neww) button = QToolButton(self) button.setIcon(QIcon(I('back.png'))) button.clicked.connect(partial(self.revert, field)) button.setToolTip(revert_tooltip % m['name']) self.widgets[field] = Widgets(neww, oldw, newl, button) for i, w in enumerate((newl, neww, button, oldw)): c = i if i < 2 else i + 1 if w is oldw: c += 1 l.addWidget(w, row, c) row += 1 self.sep = f = QFrame(self) f.setFrameShape(f.VLine) l.addWidget(f, 0, 2, row, 1) self.sep2 = f = QFrame(self) f.setFrameShape(f.VLine) l.addWidget(f, 0, 4, row, 1) def changed(self, field): w = self.widgets[field] if not w.new.same_as(w.old) and (not self.blank_as_equal or not w.new.is_blank): w.label.setFont(self.changed_font) else: w.label.setFont(QApplication.font()) def revert(self, field): widgets = self.widgets[field] neww, oldw = widgets[:2] neww.current_val = oldw.current_val def __call__(self, oldmi, newmi): self.current_mi = newmi self.initial_vals = {} for field, widgets in self.widgets.iteritems(): widgets.old.from_mi(oldmi) widgets.new.from_mi(newmi) self.initial_vals[field] = widgets.new.current_val def apply_changes(self): changed = False for field, widgets in self.widgets.iteritems(): val = widgets.new.current_val if val != self.initial_vals[field]: widgets.new.to_mi(self.current_mi) changed = True return changed
class CompareSingle(QWidget): def __init__( self, field_metadata, parent=None, revert_tooltip=None, datetime_fmt='MMMM yyyy', blank_as_equal=True, fields=('title', 'authors', 'series', 'tags', 'rating', 'publisher', 'pubdate', 'identifiers', 'languages', 'comments', 'cover')): QWidget.__init__(self, parent) self.l = l = QGridLayout() l.setContentsMargins(0, 0, 0, 0) self.setLayout(l) revert_tooltip = revert_tooltip or _('Revert %s') self.current_mi = None self.changed_font = QFont(QApplication.font()) self.changed_font.setBold(True) self.changed_font.setItalic(True) self.blank_as_equal = blank_as_equal self.widgets = OrderedDict() row = 0 for field in fields: m = field_metadata[field] dt = m['datatype'] extra = None if 'series' in {field, dt}: cls = SeriesEdit elif field == 'identifiers': cls = IdentifiersEdit elif field == 'languages': cls = LanguagesEdit elif 'comments' in {field, dt}: cls = CommentsEdit elif 'rating' in {field, dt}: cls = RatingsEdit elif dt == 'datetime': extra = datetime_fmt cls = DateEdit elif field == 'cover': cls = CoverView elif dt in {'text', 'enum'}: cls = LineEdit else: continue neww = cls(field, True, self, m, extra) neww.changed.connect(partial(self.changed, field)) oldw = cls(field, False, self, m, extra) newl = QLabel('&%s:' % m['name']) newl.setBuddy(neww) button = QToolButton(self) button.setIcon(QIcon(I('back.png'))) button.clicked.connect(partial(self.revert, field)) button.setToolTip(revert_tooltip % m['name']) self.widgets[field] = Widgets(neww, oldw, newl, button) for i, w in enumerate((newl, neww, button, oldw)): c = i if i < 2 else i + 1 if w is oldw: c += 1 l.addWidget(w, row, c) row += 1 self.sep = f = QFrame(self) f.setFrameShape(f.VLine) l.addWidget(f, 0, 2, row, 1) self.sep2 = f = QFrame(self) f.setFrameShape(f.VLine) l.addWidget(f, 0, 4, row, 1) if 'comments' in self.widgets and not gprefs.get('diff_widget_show_comments_controls', True): self.widgets['comments'].new.hide_toolbars() def save_comments_controls_state(self): if 'comments' in self.widgets: vis = self.widgets['comments'].new.toolbars_visible if vis != gprefs.get('diff_widget_show_comments_controls', True): gprefs.set('diff_widget_show_comments_controls', vis) def changed(self, field): w = self.widgets[field] if not w.new.same_as(w.old) and (not self.blank_as_equal or not w.new.is_blank): w.label.setFont(self.changed_font) else: w.label.setFont(QApplication.font()) def revert(self, field): widgets = self.widgets[field] neww, oldw = widgets[:2] neww.current_val = oldw.current_val def __call__(self, oldmi, newmi): self.current_mi = newmi self.initial_vals = {} for field, widgets in self.widgets.iteritems(): widgets.old.from_mi(oldmi) widgets.new.from_mi(newmi) self.initial_vals[field] = widgets.new.current_val def apply_changes(self): changed = False for field, widgets in self.widgets.iteritems(): val = widgets.new.current_val if val != self.initial_vals[field]: widgets.new.to_mi(self.current_mi) changed = True return changed
class MainView(QMainWindow): # Signals startPressed = pyqtSignal(bool) resetPressed = pyqtSignal() broadcastPressed = pyqtSignal(bool) def __init__(self): super(MainView, self).__init__() self.initUI() # Private variables self._running = False # ADE7753 instance self.meter = ade.ADE7753() # Connect signals and slots self.startPressed.connect(self.meter.startStopSlot) self.resetPressed.connect(self.meter.resetSlot) self.broadcastPressed.connect(self.meter.broadcastSlot) self.meter.varData.connect(self.updateData) self.meter.varPower.connect(self.updatePower) self.meter.varEnergy.connect(self.updateEnergy) # Slots # Update Vrms, Irms and Frequency @pyqtSlot(float, float, float, float) def updateData(self, vrms, irms, frequency, period): vrms = '{:.2f}'.format(vrms) irms = '{:.3f}'.format(irms) frequency = '{:.2f}'.format(frequency) self.voltageLabel.setText(vrms) self.currentLabel.setText(irms) self.frequencyLabel.setText(frequency) # Update energy @pyqtSlot(float, float, float) def updateEnergy(self, activeEnergy, apparentEnergy, reactiveEnergy): activeEnergy = '{:.3f}'.format(activeEnergy) apparentEnergy = '{:.3f}'.format(apparentEnergy) reactiveEnergy = '{:.3f}'.format(reactiveEnergy) self.activeEnergyLabel.setText(activeEnergy) self.apparentEnergyLabel.setText(apparentEnergy) self.reactiveEnergyLabel.setText(reactiveEnergy) # Update power @pyqtSlot(float, float, float) def updatePower(self, activePower, apparentPower, reactivePower): activePower = '{:.3f}'.format(activePower) apparentPower = '{:.3f}'.format(apparentPower) reactivePower = '{:.3f}'.format(reactivePower) self.activePowerLabel.setText(activePower) self.apparentPowerLabel.setText(apparentPower) self.reactivePowerLabel.setText(reactivePower) def initUI(self): # Set central widget centralWidget = QWidget() self.setCentralWidget(centralWidget) # Load LCD fonts lcdNumbersFontID = QFontDatabase().addApplicationFont("lcdmn.ttf") #fontNames = QFontDatabase().applicationFontFamilies(lcdNumbersFontID) # Change font size and use italic for strings #self.lcdNumbersFont = QFont(fontNames[0]) self.lcdNumbersFont = QFont() self.lcdNumbersFont.setPointSize(40) #self.lcdStringFont = QFont(fontNames[0]) self.lcdStringFont = QFont() self.lcdStringFont.setPointSize(35) self.lcdStringFont.setItalic(True) # self.lcdBoldFont = QFont(fontNames[0]) self.lcdBoldFont = QFont() self.lcdBoldFont.setPointSize(50) self.lcdBoldFont.setBold(True) # Labels dataLabel = QLabel("DATA") dataLabel.setStyleSheet(""" QLabel {color:red} """) energyLabel = QLabel("ENERGY") energyLabel.setStyleSheet(""" QLabel {color:red} """) powerLabel = QLabel("POWER") powerLabel.setStyleSheet(""" QLabel {color:red} """) dataLabel.setFont(self.lcdBoldFont) powerLabel.setFont(self.lcdBoldFont) energyLabel.setFont(self.lcdBoldFont) self.voltageLabel = QLabel("0.00") self.voltageLabel.setFont(self.lcdNumbersFont) self.voltageString = QLabel("V") self.voltageString.setFont(self.lcdStringFont) self.currentLabel = QLabel("0.00") self.currentLabel.setFont(self.lcdNumbersFont) self.currentString = QLabel("A") self.currentString.setFont(self.lcdStringFont) self.frequencyLabel = QLabel("0.00") self.frequencyLabel.setFont(self.lcdNumbersFont) self.frequencyString = QLabel("Hz") self.frequencyString.setFont(self.lcdStringFont) self.activeEnergyLabel = QLabel("0.00") self.activeEnergyLabel.setFont(self.lcdNumbersFont) self.activeEnergyString = QLabel("Wh") self.activeEnergyString.setFont(self.lcdStringFont) self.apparentEnergyLabel = QLabel("0.00") self.apparentEnergyLabel.setFont(self.lcdNumbersFont) self.apparentEnergyString = QLabel("VAh") self.apparentEnergyString.setFont(self.lcdStringFont) self.reactiveEnergyLabel = QLabel("0.00") self.reactiveEnergyLabel.setFont(self.lcdNumbersFont) self.reactiveEnergyString = QLabel("VARh") self.reactiveEnergyString.setFont(self.lcdStringFont) self.activePowerLabel = QLabel("0.00") self.activePowerLabel.setFont(self.lcdNumbersFont) self.activePowerString = QLabel("W") self.activePowerString.setFont(self.lcdStringFont) self.apparentPowerLabel = QLabel("0.00") self.apparentPowerLabel.setFont(self.lcdNumbersFont) self.apparentPowerString = QLabel("VA") self.apparentPowerString.setFont(self.lcdStringFont) self.reactivePowerLabel = QLabel("0.00") self.reactivePowerLabel.setFont(self.lcdNumbersFont) self.reactivePowerString = QLabel("VAR") self.reactivePowerString.setFont(self.lcdStringFont) # Horizontal lines hline1 = self.HLine() hline2 = self.HLine() hline3 = self.HLine() hline4 = self.HLine() # Vertical lines vline1 = self.VLine() vline2 = self.VLine() vline3 = self.VLine() # Central grid layout for central widget self.centralGridLayout = QGridLayout(self.centralWidget()) self.centralGridLayout.setHorizontalSpacing(20) self.centralGridLayout.setVerticalSpacing(5) # Add labels self.centralGridLayout.addWidget(dataLabel,0,0,1,2, QtCore.Qt.AlignCenter) self.centralGridLayout.addWidget(energyLabel,0,3,1,2, QtCore.Qt.AlignCenter) self.centralGridLayout.addWidget(powerLabel,0,6,1,2, QtCore.Qt.AlignCenter) self.centralGridLayout.addWidget(hline1, 1, 0, 1, -1) self.centralGridLayout.addWidget(self.voltageLabel, 2, 0, 1, 1, QtCore.Qt.AlignLeft) self.centralGridLayout.addWidget(self.voltageString, 2, 1, 1, 1, QtCore.Qt.AlignLeft) self.centralGridLayout.addWidget(hline2, 3, 0, 1, -1) self.centralGridLayout.addWidget(self.currentLabel, 4, 0, 1, 1, QtCore.Qt.AlignLeft) self.centralGridLayout.addWidget(self.currentString, 4, 1, 1, 1, QtCore.Qt.AlignLeft) self.centralGridLayout.addWidget(hline3, 5, 0, 1, -1) self.centralGridLayout.addWidget(self.frequencyLabel, 6, 0, 1, 1, QtCore.Qt.AlignLeft) self.centralGridLayout.addWidget(self.frequencyString, 6, 1, 1, 1, QtCore.Qt.AlignLeft) self.centralGridLayout.addWidget(hline4, 7, 0, 1, -1) self.centralGridLayout.addWidget(vline1, 0, 2, -1, 1) self.centralGridLayout.addWidget(self.activeEnergyLabel, 2, 3, 1, 1, QtCore.Qt.AlignLeft) self.centralGridLayout.addWidget(self.activeEnergyString, 2, 4, 1, 1, QtCore.Qt.AlignLeft) self.centralGridLayout.addWidget(self.apparentEnergyLabel, 4, 3, 1, 1, QtCore.Qt.AlignLeft) self.centralGridLayout.addWidget(self.apparentEnergyString, 4, 4, 1, 1, QtCore.Qt.AlignLeft) self.centralGridLayout.addWidget(self.reactiveEnergyLabel, 6, 3, 1, 1, QtCore.Qt.AlignLeft) self.centralGridLayout.addWidget(self.reactiveEnergyString, 6, 4, 1, 1, QtCore.Qt.AlignLeft) self.centralGridLayout.addWidget(vline2, 0, 5, -1, 1) self.centralGridLayout.addWidget(self.activePowerLabel, 2, 6, 1, 1, QtCore.Qt.AlignLeft) self.centralGridLayout.addWidget(self.activePowerString, 2, 7, 1, 1, QtCore.Qt.AlignLeft) self.centralGridLayout.addWidget(self.apparentPowerLabel, 4, 6, 1, 1, QtCore.Qt.AlignLeft) self.centralGridLayout.addWidget(self.apparentPowerString, 4, 7, 1, 1, QtCore.Qt.AlignLeft) self.centralGridLayout.addWidget(self.reactivePowerLabel, 6, 6, 1, 1, QtCore.Qt.AlignLeft) self.centralGridLayout.addWidget(self.reactivePowerString, 6, 7, 1, 1, QtCore.Qt.AlignLeft) # self.centralGridLayout.addWidget(vline3, 0, 8, -1, 1) # Buttons self.startStopButton = QPushButton("START") self.startStopButton.setFont(self.lcdStringFont) buttonPolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed) self.startStopButton.setSizePolicy(buttonPolicy) self.startStopButton.clicked.connect(self.startStopClicked) self.resetButton = QPushButton("RESET") self.resetButton.setFont(self.lcdStringFont) self.resetButton.setSizePolicy(buttonPolicy) self.resetButton.clicked.connect(self.resetButtonClicked) self.broadcastButton = QPushButton("BROADCAST") self.broadcastButton.setFont(self.lcdStringFont) self.broadcastButton.setSizePolicy(buttonPolicy) self.broadcastButton.setCheckable(True) self.broadcastButton.toggled.connect(self.broadcastButtonClicked) self.centralGridLayout.addWidget(self.startStopButton, 8, 0, 1, 2) self.centralGridLayout.addWidget(self.resetButton, 8, 3, 1, 2) self.centralGridLayout.addWidget(self.broadcastButton, 8, 6, 1, 2) # Status bar and show window self.statusBar().showMessage('Ready') self.setWindowTitle("ADE7753 Power Meter") self.show() # Button slots def startStopClicked(self): if(self._running): self._running = False self.startStopButton.setText("START") self.startPressed.emit(False) else: self._running = True self.startStopButton.setText("STOP") self.startPressed.emit(True) def resetButtonClicked(self): self.resetPressed.emit() def broadcastButtonClicked(self, s): self.broadcastPressed.emit(s) # Helper functions def HLine(self): line = QFrame() line.setFrameStyle(QFrame.HLine) line.setFrameShape(QFrame.HLine) line.setFrameShadow(QFrame.Sunken) return line def VLine(self): line = QFrame() line.setFrameStyle(QFrame.VLine) line.setFrameShape(QFrame.VLine) line.setFrameShadow(QFrame.Sunken) return line
class CompareSingle(QWidget): def __init__( self, field_metadata, parent=None, revert_tooltip=None, datetime_fmt="MMMM yyyy", blank_as_equal=True, fields=( "title", "authors", "series", "tags", "rating", "publisher", "pubdate", "identifiers", "languages", "comments", "cover", ), ): QWidget.__init__(self, parent) self.l = l = QGridLayout() l.setContentsMargins(0, 0, 0, 0) self.setLayout(l) revert_tooltip = revert_tooltip or _("Revert %s") self.current_mi = None self.changed_font = QFont(QApplication.font()) self.changed_font.setBold(True) self.changed_font.setItalic(True) self.blank_as_equal = blank_as_equal self.widgets = OrderedDict() row = 0 for field in fields: m = field_metadata[field] dt = m["datatype"] extra = None if "series" in {field, dt}: cls = SeriesEdit elif field == "identifiers": cls = IdentifiersEdit elif field == "languages": cls = LanguagesEdit elif "comments" in {field, dt}: cls = CommentsEdit elif "rating" in {field, dt}: cls = RatingsEdit elif dt == "datetime": extra = datetime_fmt cls = DateEdit elif field == "cover": cls = CoverView elif dt in {"text", "enum"}: cls = LineEdit else: continue neww = cls(field, True, self, m, extra) neww.changed.connect(partial(self.changed, field)) oldw = cls(field, False, self, m, extra) newl = QLabel("&%s:" % m["name"]) newl.setBuddy(neww) button = QToolButton(self) button.setIcon(QIcon(I("back.png"))) button.clicked.connect(partial(self.revert, field)) button.setToolTip(revert_tooltip % m["name"]) self.widgets[field] = Widgets(neww, oldw, newl, button) for i, w in enumerate((newl, neww, button, oldw)): c = i if i < 2 else i + 1 if w is oldw: c += 1 l.addWidget(w, row, c) row += 1 self.sep = f = QFrame(self) f.setFrameShape(f.VLine) l.addWidget(f, 0, 2, row, 1) self.sep2 = f = QFrame(self) f.setFrameShape(f.VLine) l.addWidget(f, 0, 4, row, 1) def changed(self, field): w = self.widgets[field] if not w.new.same_as(w.old) and (not self.blank_as_equal or not w.new.is_blank): w.label.setFont(self.changed_font) else: w.label.setFont(QApplication.font()) def revert(self, field): widgets = self.widgets[field] neww, oldw = widgets[:2] neww.current_val = oldw.current_val def __call__(self, oldmi, newmi): self.current_mi = newmi self.initial_vals = {} for field, widgets in self.widgets.iteritems(): widgets.old.from_mi(oldmi) widgets.new.from_mi(newmi) self.initial_vals[field] = widgets.new.current_val def apply_changes(self): changed = False for field, widgets in self.widgets.iteritems(): val = widgets.new.current_val if val != self.initial_vals[field]: widgets.new.to_mi(self.current_mi) changed = True return changed