More QVariant porting

This commit is contained in:
Kovid Goyal 2014-04-24 10:33:54 +05:30
parent 8518d8f7dc
commit 6621bd7357
15 changed files with 103 additions and 110 deletions

View File

@ -8,7 +8,7 @@ __docformat__ = 'restructuredtext en'
import textwrap import textwrap
from PyQt5.Qt import (QWidget, pyqtSignal, QCheckBox, QAbstractSpinBox, from PyQt5.Qt import (QWidget, pyqtSignal, QCheckBox, QAbstractSpinBox,
QLineEdit, QComboBox, QVariant, Qt, QIcon, QDialog, QVBoxLayout, QLineEdit, QComboBox, Qt, QIcon, QDialog, QVBoxLayout,
QDialogButtonBox) QDialogButtonBox)
from calibre.customize.ui import preferences_plugins from calibre.customize.ui import preferences_plugins
@ -142,7 +142,7 @@ class Setting(object):
for x in choices: for x in choices:
if isinstance(x, basestring): if isinstance(x, basestring):
x = (x, x) x = (x, x)
self.gui_obj.addItem(x[0], QVariant(x[1])) self.gui_obj.addItem(x[0], (x[1]))
self.set_gui_val(self.get_config_val(default=False)) self.set_gui_val(self.get_config_val(default=False))
self.gui_obj.blockSignals(False) self.gui_obj.blockSignals(False)
self.initial_value = self.get_gui_val() self.initial_value = self.get_gui_val()
@ -179,7 +179,7 @@ class Setting(object):
if isinstance(self.gui_obj, EditWithComplete): if isinstance(self.gui_obj, EditWithComplete):
self.gui_obj.setText(val) self.gui_obj.setText(val)
else: else:
idx = self.gui_obj.findData(QVariant(val), role=Qt.UserRole, idx = self.gui_obj.findData((val), role=Qt.UserRole,
flags=self.CHOICES_SEARCH_FLAGS) flags=self.CHOICES_SEARCH_FLAGS)
if idx == -1: if idx == -1:
idx = 0 idx = 0
@ -200,7 +200,7 @@ class Setting(object):
else: else:
idx = self.gui_obj.currentIndex() idx = self.gui_obj.currentIndex()
if idx < 0: idx = 0 if idx < 0: idx = 0
val = unicode(self.gui_obj.itemData(idx).toString()) val = unicode(self.gui_obj.itemData(idx) or '')
return val return val
class CommaSeparatedList(Setting): class CommaSeparatedList(Setting):

View File

@ -7,7 +7,7 @@ __docformat__ = 'restructuredtext en'
import re import re
from PyQt5.Qt import Qt, QVariant, QListWidgetItem from PyQt5.Qt import Qt, QListWidgetItem
from calibre.gui2.preferences import ConfigWidgetBase, test_widget, Setting from calibre.gui2.preferences import ConfigWidgetBase, test_widget, Setting
from calibre.gui2.preferences.behavior_ui import Ui_Form from calibre.gui2.preferences.behavior_ui import Ui_Form
@ -81,7 +81,7 @@ class ConfigWidget(ConfigWidgetBase, Ui_Form):
def commit(self): def commit(self):
input_map = prefs['input_format_order'] input_map = prefs['input_format_order']
input_cols = [unicode(self.opt_input_order.item(i).data(Qt.UserRole).toString()) for input_cols = [unicode(self.opt_input_order.item(i).data(Qt.UserRole) or '') for
i in range(self.opt_input_order.count())] i in range(self.opt_input_order.count())]
if input_map != input_cols: if input_map != input_cols:
prefs['input_format_order'] = input_cols prefs['input_format_order'] = input_cols
@ -142,7 +142,7 @@ class ConfigWidget(ConfigWidgetBase, Ui_Form):
all_formats.add(fmt.upper()) all_formats.add(fmt.upper())
for format in input_map + list(all_formats.difference(input_map)): for format in input_map + list(all_formats.difference(input_map)):
item = QListWidgetItem(format, self.opt_input_order) item = QListWidgetItem(format, self.opt_input_order)
item.setData(Qt.UserRole, QVariant(format)) item.setData(Qt.UserRole, (format))
item.setFlags(Qt.ItemIsEnabled|Qt.ItemIsSelectable) item.setFlags(Qt.ItemIsEnabled|Qt.ItemIsSelectable)
def up_input(self, *args): def up_input(self, *args):

View File

@ -140,10 +140,10 @@ class ConditionEditor(QWidget): # {{{
def current_col(self): def current_col(self):
def fget(self): def fget(self):
idx = self.column_box.currentIndex() idx = self.column_box.currentIndex()
return unicode(self.column_box.itemData(idx).toString()) return unicode(self.column_box.itemData(idx) or '')
def fset(self, val): def fset(self, val):
for idx in range(self.column_box.count()): for idx in range(self.column_box.count()):
c = unicode(self.column_box.itemData(idx).toString()) c = unicode(self.column_box.itemData(idx) or '')
if c == val: if c == val:
self.column_box.setCurrentIndex(idx) self.column_box.setCurrentIndex(idx)
return return
@ -154,10 +154,10 @@ class ConditionEditor(QWidget): # {{{
def current_action(self): def current_action(self):
def fget(self): def fget(self):
idx = self.action_box.currentIndex() idx = self.action_box.currentIndex()
return unicode(self.action_box.itemData(idx).toString()) return unicode(self.action_box.itemData(idx) or '')
def fset(self, val): def fset(self, val):
for idx in range(self.action_box.count()): for idx in range(self.action_box.count()):
c = unicode(self.action_box.itemData(idx).toString()) c = unicode(self.action_box.itemData(idx) or '')
if c == val: if c == val:
self.action_box.setCurrentIndex(idx) self.action_box.setCurrentIndex(idx)
return return
@ -595,7 +595,7 @@ class RuleEditor(QDialog): # {{{
self.update_icon_filenames_in_box() self.update_icon_filenames_in_box()
for i in range(self.column_box.count()): for i in range(self.column_box.count()):
c = unicode(self.column_box.itemData(i).toString()) c = unicode(self.column_box.itemData(i) or '')
if col == c: if col == c:
self.column_box.setCurrentIndex(i) self.column_box.setCurrentIndex(i)
break break
@ -649,14 +649,14 @@ class RuleEditor(QDialog): # {{{
else: else:
r.color = self.color_box.color r.color = self.color_box.color
idx = self.column_box.currentIndex() idx = self.column_box.currentIndex()
col = unicode(self.column_box.itemData(idx).toString()) col = unicode(self.column_box.itemData(idx) or '')
for c in self.conditions: for c in self.conditions:
condition = c.condition condition = c.condition
if condition is not None: if condition is not None:
r.add_condition(*condition) r.add_condition(*condition)
if self.rule_kind == 'icon': if self.rule_kind == 'icon':
kind = unicode(self.kind_box.itemData( kind = unicode(self.kind_box.itemData(
self.kind_box.currentIndex()).toString()) self.kind_box.currentIndex()) or '')
else: else:
kind = self.rule_kind kind = self.rule_kind

View File

@ -7,7 +7,7 @@ __docformat__ = 'restructuredtext en'
import copy, sys import copy, sys
from PyQt5.Qt import Qt, QVariant, QListWidgetItem, QIcon from PyQt5.Qt import Qt, QListWidgetItem, QIcon
from calibre.gui2.preferences import ConfigWidgetBase, test_widget from calibre.gui2.preferences import ConfigWidgetBase, test_widget
from calibre.gui2.preferences.columns_ui import Ui_Form from calibre.gui2.preferences.columns_ui import Ui_Form
@ -66,9 +66,9 @@ class ConfigWidget(ConfigWidgetBase, Ui_Form):
self.opt_columns.clear() self.opt_columns.clear()
for col in colmap: for col in colmap:
item = QListWidgetItem(model.headers[col], self.opt_columns) item = QListWidgetItem(model.headers[col], self.opt_columns)
item.setData(Qt.UserRole, QVariant(col)) item.setData(Qt.UserRole, (col))
if col.startswith('#'): if col.startswith('#'):
item.setData(Qt.DecorationRole, QVariant(QIcon(I('column.png')))) item.setData(Qt.DecorationRole, (QIcon(I('column.png'))))
flags = Qt.ItemIsEnabled|Qt.ItemIsSelectable flags = Qt.ItemIsEnabled|Qt.ItemIsSelectable
if col != 'ondevice': if col != 'ondevice':
flags |= Qt.ItemIsUserCheckable flags |= Qt.ItemIsUserCheckable
@ -97,7 +97,7 @@ class ConfigWidget(ConfigWidgetBase, Ui_Form):
if idx < 0: if idx < 0:
return error_dialog(self, '', _('You must select a column to delete it'), return error_dialog(self, '', _('You must select a column to delete it'),
show=True) show=True)
col = unicode(self.opt_columns.item(idx).data(Qt.UserRole).toString()) col = unicode(self.opt_columns.item(idx).data(Qt.UserRole) or '')
if col not in self.custcols: if col not in self.custcols:
return error_dialog(self, '', return error_dialog(self, '',
_('The selected column is not a custom column'), show=True) _('The selected column is not a custom column'), show=True)
@ -126,12 +126,12 @@ class ConfigWidget(ConfigWidgetBase, Ui_Form):
def apply_custom_column_changes(self): def apply_custom_column_changes(self):
model = self.gui.library_view.model() model = self.gui.library_view.model()
db = model.db db = model.db
config_cols = [unicode(self.opt_columns.item(i).data(Qt.UserRole).toString())\ config_cols = [unicode(self.opt_columns.item(i).data(Qt.UserRole) or '')\
for i in range(self.opt_columns.count())] for i in range(self.opt_columns.count())]
if not config_cols: if not config_cols:
config_cols = ['title'] config_cols = ['title']
removed_cols = set(model.column_map) - set(config_cols) removed_cols = set(model.column_map) - set(config_cols)
hidden_cols = set([unicode(self.opt_columns.item(i).data(Qt.UserRole).toString())\ hidden_cols = set([unicode(self.opt_columns.item(i).data(Qt.UserRole) or '')\
for i in range(self.opt_columns.count()) \ for i in range(self.opt_columns.count()) \
if self.opt_columns.item(i).checkState()==Qt.Unchecked]) if self.opt_columns.item(i).checkState()==Qt.Unchecked])
hidden_cols = hidden_cols.union(removed_cols) # Hide removed cols hidden_cols = hidden_cols.union(removed_cols) # Hide removed cols

View File

@ -7,7 +7,7 @@ __docformat__ = 'restructuredtext en'
import importlib import importlib
from PyQt5.Qt import QIcon, Qt, QStringListModel, QVariant from PyQt5.Qt import QIcon, Qt, QStringListModel
from calibre.gui2.preferences import ConfigWidgetBase, test_widget, AbortCommit from calibre.gui2.preferences import ConfigWidgetBase, test_widget, AbortCommit
from calibre.ebooks.conversion.plumber import Plumber from calibre.ebooks.conversion.plumber import Plumber
@ -33,7 +33,7 @@ class Model(QStringListModel):
if role == Qt.DecorationRole: if role == Qt.DecorationRole:
w = self.widgets[index.row()] w = self.widgets[index.row()]
if w.ICON: if w.ICON:
return QVariant(QIcon(w.ICON)) return (QIcon(w.ICON))
return QStringListModel.data(self, index, role) return QStringListModel.data(self, index, role)
class Base(ConfigWidgetBase, Ui_Form): class Base(ConfigWidgetBase, Ui_Form):

View File

@ -6,7 +6,7 @@ __copyright__ = '2010, Kovid Goyal <kovid at kovidgoyal.net>'
import re import re
from functools import partial from functools import partial
from PyQt5.Qt import QDialog, Qt, QListWidgetItem, QVariant, QColor, QIcon from PyQt5.Qt import QDialog, Qt, QListWidgetItem, QColor, QIcon
from calibre.gui2.preferences.create_custom_column_ui import Ui_QCreateCustomColumn from calibre.gui2.preferences.create_custom_column_ui import Ui_QCreateCustomColumn
from calibre.gui2 import error_dialog from calibre.gui2 import error_dialog
@ -101,7 +101,7 @@ class CreateCustomColumn(QDialog, Ui_QCreateCustomColumn):
self.simple_error(_('No column selected'), self.simple_error(_('No column selected'),
_('No column has been selected')) _('No column has been selected'))
return return
col = unicode(parent.opt_columns.item(idx).data(Qt.UserRole).toString()) col = unicode(parent.opt_columns.item(idx).data(Qt.UserRole) or '')
if col not in parent.custcols: if col not in parent.custcols:
self.simple_error('', _('Selected column is not a user-defined column')) self.simple_error('', _('Selected column is not a user-defined column'))
return return
@ -324,8 +324,8 @@ class CreateCustomColumn(QDialog, Ui_QCreateCustomColumn):
'is_multiple':is_multiple, 'is_multiple':is_multiple,
} }
item = QListWidgetItem(col_heading, self.parent.opt_columns) item = QListWidgetItem(col_heading, self.parent.opt_columns)
item.setData(Qt.UserRole, QVariant(key)) item.setData(Qt.UserRole, (key))
item.setData(Qt.DecorationRole, QVariant(QIcon(I('column.png')))) item.setData(Qt.DecorationRole, (QIcon(I('column.png'))))
item.setFlags(Qt.ItemIsEnabled|Qt.ItemIsUserCheckable|Qt.ItemIsSelectable) item.setFlags(Qt.ItemIsEnabled|Qt.ItemIsUserCheckable|Qt.ItemIsSelectable)
item.setCheckState(Qt.Checked) item.setCheckState(Qt.Checked)
else: else:

View File

@ -7,14 +7,14 @@ __docformat__ = 'restructuredtext en'
import textwrap import textwrap
from PyQt5.Qt import QAbstractTableModel, QVariant, QFont, Qt from PyQt5.Qt import QAbstractTableModel, QFont, Qt
from calibre.gui2.preferences import ConfigWidgetBase, test_widget, \ from calibre.gui2.preferences import ConfigWidgetBase, test_widget, \
AbortCommit AbortCommit
from calibre.gui2.preferences.email_ui import Ui_Form from calibre.gui2.preferences.email_ui import Ui_Form
from calibre.utils.config import ConfigProxy from calibre.utils.config import ConfigProxy
from calibre.gui2 import NONE, gprefs from calibre.gui2 import gprefs
from calibre.utils.smtp import config as smtp_prefs from calibre.utils.smtp import config as smtp_prefs
class EmailAccounts(QAbstractTableModel): # {{{ class EmailAccounts(QAbstractTableModel): # {{{
@ -25,12 +25,12 @@ class EmailAccounts(QAbstractTableModel): # {{{
self.subjects = subjects self.subjects = subjects
self.aliases = aliases self.aliases = aliases
self.account_order = sorted(self.accounts.keys()) self.account_order = sorted(self.accounts.keys())
self.headers = map(QVariant, [_('Email'), _('Formats'), _('Subject'), self.headers = map(unicode, [_('Email'), _('Formats'), _('Subject'),
_('Auto send'), _('Alias')]) _('Auto send'), _('Alias')])
self.default_font = QFont() self.default_font = QFont()
self.default_font.setBold(True) self.default_font.setBold(True)
self.default_font = QVariant(self.default_font) self.default_font = (self.default_font)
self.tooltips =[NONE] + list(map(QVariant, map(textwrap.fill, self.tooltips =[None] + list(map(unicode, map(textwrap.fill,
[_('Formats to email. The first matching format will be sent.'), [_('Formats to email. The first matching format will be sent.'),
_('Subject of the email to use when sending. When left blank ' _('Subject of the email to use when sending. When left blank '
'the title will be used for the subject. Also, the same ' 'the title will be used for the subject. Also, the same '
@ -51,33 +51,33 @@ class EmailAccounts(QAbstractTableModel): # {{{
def headerData(self, section, orientation, role): def headerData(self, section, orientation, role):
if role == Qt.DisplayRole and orientation == Qt.Horizontal: if role == Qt.DisplayRole and orientation == Qt.Horizontal:
return self.headers[section] return self.headers[section]
return NONE return None
def data(self, index, role): def data(self, index, role):
row, col = index.row(), index.column() row, col = index.row(), index.column()
if row < 0 or row >= self.rowCount(): if row < 0 or row >= self.rowCount():
return NONE return None
account = self.account_order[row] account = self.account_order[row]
if account not in self.accounts: if account not in self.accounts:
return NONE return None
if role == Qt.UserRole: if role == Qt.UserRole:
return (account, self.accounts[account]) return (account, self.accounts[account])
if role == Qt.ToolTipRole: if role == Qt.ToolTipRole:
return self.tooltips[col] return self.tooltips[col]
if role in [Qt.DisplayRole, Qt.EditRole]: if role in [Qt.DisplayRole, Qt.EditRole]:
if col == 0: if col == 0:
return QVariant(account) return (account)
if col == 1: if col == 1:
return QVariant(self.accounts[account][0]) return (self.accounts[account][0])
if col == 2: if col == 2:
return QVariant(self.subjects.get(account, '')) return (self.subjects.get(account, ''))
if col == 4: if col == 4:
return QVariant(self.aliases.get(account, '')) return (self.aliases.get(account, ''))
if role == Qt.FontRole and self.accounts[account][2]: if role == Qt.FontRole and self.accounts[account][2]:
return self.default_font return self.default_font
if role == Qt.CheckStateRole and col == 3: if role == Qt.CheckStateRole and col == 3:
return QVariant(Qt.Checked if self.accounts[account][1] else Qt.Unchecked) return (Qt.Checked if self.accounts[account][1] else Qt.Unchecked)
return NONE return None
def flags(self, index): def flags(self, index):
if index.column() == 3: if index.column() == 3:
@ -93,16 +93,16 @@ class EmailAccounts(QAbstractTableModel): # {{{
if col == 3: if col == 3:
self.accounts[account][1] ^= True self.accounts[account][1] ^= True
elif col == 2: elif col == 2:
self.subjects[account] = unicode(value.toString()) self.subjects[account] = unicode(value or '')
elif col == 4: elif col == 4:
self.aliases.pop(account, None) self.aliases.pop(account, None)
aval = unicode(value.toString()).strip() aval = unicode(value or '').strip()
if aval: if aval:
self.aliases[account] = aval self.aliases[account] = aval
elif col == 1: elif col == 1:
self.accounts[account][0] = unicode(value.toString()).upper() self.accounts[account][0] = unicode(value or '').upper()
elif col == 0: elif col == 0:
na = unicode(value.toString()) na = unicode(value or '')
from email.utils import parseaddr from email.utils import parseaddr
addr = parseaddr(na)[-1] addr = parseaddr(na)[-1]
if not addr: if not addr:

View File

@ -79,7 +79,7 @@ class ConfigWidget(ConfigWidgetBase):
devs = {} devs = {}
for i in xrange(0, self.devices.count()): for i in xrange(0, self.devices.count()):
e = self.devices.item(i) e = self.devices.item(i)
dev, uid = e.data(Qt.UserRole).toPyObject() dev, uid = e.data(Qt.UserRole)
if dev not in devs: if dev not in devs:
devs[dev] = [] devs[dev] = []
if e.checkState() == Qt.Checked: if e.checkState() == Qt.Checked:
@ -90,11 +90,11 @@ class ConfigWidget(ConfigWidgetBase):
for i in xrange(self.device_plugins.count()): for i in xrange(self.device_plugins.count()):
e = self.device_plugins.item(i) e = self.device_plugins.item(i)
dev = e.data(Qt.UserRole).toPyObject() dev = e.data(Qt.UserRole)
if e.checkState() == Qt.Unchecked: if e.checkState() == Qt.Unchecked:
enable_plugin(dev) enable_plugin(dev)
return True # Restart required return True # Restart required
if __name__ == '__main__': if __name__ == '__main__':
from PyQt5.Qt import QApplication from PyQt5.Qt import QApplication

View File

@ -16,7 +16,7 @@ from PyQt5.Qt import (
from calibre import human_readable from calibre import human_readable
from calibre.gui2.preferences import ConfigWidgetBase, test_widget, CommaSeparatedList from calibre.gui2.preferences import ConfigWidgetBase, test_widget, CommaSeparatedList
from calibre.gui2.preferences.look_feel_ui import Ui_Form from calibre.gui2.preferences.look_feel_ui import Ui_Form
from calibre.gui2 import config, gprefs, qt_app, NONE, open_local_file, question_dialog from calibre.gui2 import config, gprefs, qt_app, open_local_file, question_dialog
from calibre.utils.localization import (available_translations, from calibre.utils.localization import (available_translations,
get_language, get_lang) get_language, get_lang)
from calibre.utils.config import prefs from calibre.utils.config import prefs
@ -49,7 +49,7 @@ class DisplayedFields(QAbstractListModel): # {{{
try: try:
field, visible = self.fields[index.row()] field, visible = self.fields[index.row()]
except: except:
return NONE return None
if role == Qt.DisplayRole: if role == Qt.DisplayRole:
name = field name = field
try: try:
@ -63,7 +63,7 @@ class DisplayedFields(QAbstractListModel): # {{{
return Qt.Checked if visible else Qt.Unchecked return Qt.Checked if visible else Qt.Unchecked
if role == Qt.DecorationRole and field.startswith('#'): if role == Qt.DecorationRole and field.startswith('#'):
return QIcon(I('column.png')) return QIcon(I('column.png'))
return NONE return None
def flags(self, index): def flags(self, index):
ans = QAbstractListModel.flags(self, index) ans = QAbstractListModel.flags(self, index)
@ -72,12 +72,10 @@ class DisplayedFields(QAbstractListModel): # {{{
def setData(self, index, val, role): def setData(self, index, val, role):
ret = False ret = False
if role == Qt.CheckStateRole: if role == Qt.CheckStateRole:
val, ok = val.toInt() self.fields[index.row()][1] = bool(val)
if ok: self.changed = True
self.fields[index.row()][1] = bool(val) ret = True
self.changed = True self.dataChanged.emit(index, index)
ret = True
self.dataChanged.emit(index, index)
return ret return ret
def restore_defaults(self): def restore_defaults(self):

View File

@ -17,7 +17,7 @@ from calibre.gui2.preferences.metadata_sources_ui import Ui_Form
from calibre.ebooks.metadata.sources.prefs import msprefs from calibre.ebooks.metadata.sources.prefs import msprefs
from calibre.customize.ui import (all_metadata_plugins, is_disabled, from calibre.customize.ui import (all_metadata_plugins, is_disabled,
enable_plugin, disable_plugin, default_disabled_plugins) enable_plugin, disable_plugin, default_disabled_plugins)
from calibre.gui2 import NONE, error_dialog, question_dialog from calibre.gui2 import error_dialog, question_dialog
class SourcesModel(QAbstractTableModel): # {{{ class SourcesModel(QAbstractTableModel): # {{{
@ -49,13 +49,13 @@ class SourcesModel(QAbstractTableModel): # {{{
return _('Source') return _('Source')
if section == 1: if section == 1:
return _('Cover priority') return _('Cover priority')
return NONE return None
def data(self, index, role): def data(self, index, role):
try: try:
plugin = self.plugins[index.row()] plugin = self.plugins[index.row()]
except: except:
return NONE return None
col = index.column() col = index.column()
if role == Qt.DisplayRole: if role == Qt.DisplayRole:
@ -77,7 +77,7 @@ class SourcesModel(QAbstractTableModel): # {{{
if plugin.is_configured(): if plugin.is_configured():
return base + _('This source is configured and ready to go') return base + _('This source is configured and ready to go')
return base + _('This source needs configuration') return base + _('This source needs configuration')
return NONE return None
def setData(self, index, val, role): def setData(self, index, val, role):
try: try:
@ -87,24 +87,20 @@ class SourcesModel(QAbstractTableModel): # {{{
col = index.column() col = index.column()
ret = False ret = False
if col == 0 and role == Qt.CheckStateRole: if col == 0 and role == Qt.CheckStateRole:
val, ok = val.toInt() if val == Qt.Checked and 'Douban' in plugin.name:
if ok: if not question_dialog(self.gui_parent,
if val == Qt.Checked and 'Douban' in plugin.name: _('Are you sure?'), '<p>'+
if not question_dialog(self.gui_parent, _('This plugin is useful only for <b>Chinese</b>'
_('Are you sure?'), '<p>'+ ' language books. It can return incorrect'
_('This plugin is useful only for <b>Chinese</b>' ' results for books in English. Are you'
' language books. It can return incorrect' ' sure you want to enable it?'),
' results for books in English. Are you' show_copy_button=False):
' sure you want to enable it?'), return ret
show_copy_button=False): self.enabled_overrides[plugin] = int(val)
return ret ret = True
self.enabled_overrides[plugin] = val
ret = True
if col == 1 and role == Qt.EditRole: if col == 1 and role == Qt.EditRole:
val, ok = val.toInt() self.cover_overrides[plugin] = int(val)
if ok: ret = True
self.cover_overrides[plugin] = val
ret = True
if ret: if ret:
self.dataChanged.emit(index, index) self.dataChanged.emit(index, index)
return ret return ret
@ -197,7 +193,7 @@ class FieldsModel(QAbstractListModel): # {{{
return self.descs.get(field, field) return self.descs.get(field, field)
if role == Qt.CheckStateRole: if role == Qt.CheckStateRole:
return self.overrides.get(field, self.state(field)) return self.overrides.get(field, self.state(field))
return NONE return None
def flags(self, index): def flags(self, index):
ans = QAbstractTableModel.flags(self, index) ans = QAbstractTableModel.flags(self, index)
@ -225,10 +221,8 @@ class FieldsModel(QAbstractListModel): # {{{
return False return False
ret = False ret = False
if role == Qt.CheckStateRole: if role == Qt.CheckStateRole:
val, ok = val.toInt() self.overrides[field] = int(val)
if ok: ret = True
self.overrides[field] = val
ret = True
if ret: if ret:
self.dataChanged.emit(index, index) self.dataChanged.emit(index, index)
return ret return ret
@ -326,7 +320,7 @@ class ConfigWidget(ConfigWidgetBase, Ui_Form):
def configure_plugin(self): def configure_plugin(self):
for index in self.sources_view.selectionModel().selectedRows(): for index in self.sources_view.selectionModel().selectedRows():
plugin = self.sources_model.data(index, Qt.UserRole) plugin = self.sources_model.data(index, Qt.UserRole)
if plugin is not NONE: if plugin is not None:
return self.do_config(plugin) return self.do_config(plugin)
error_dialog(self, _('No source selected'), error_dialog(self, _('No source selected'),
_('No source selected, cannot configure.'), show=True) _('No source selected, cannot configure.'), show=True)

View File

@ -286,7 +286,7 @@ class ConfigWidget(ConfigWidgetBase, Ui_Form):
validation_formatter.validate(s) validation_formatter.validate(s)
except Exception as err: except Exception as err:
error_dialog(self, _('Invalid template'), error_dialog(self, _('Invalid template'),
'<p>'+_('The template %s is invalid:')%s + \ '<p>'+_('The template %s is invalid:')%s +
'<br>'+str(err), show=True) '<br>'+str(err), show=True)
return return
pb.append((s, self.dest_fields[d])) pb.append((s, self.dest_fields[d]))
@ -321,7 +321,7 @@ class ConfigWidget(ConfigWidgetBase, Ui_Form):
self.refill_all_boxes() self.refill_all_boxes()
def existing_pb_clicked(self, Qitem): def existing_pb_clicked(self, Qitem):
item = Qitem.data(Qt.UserRole).toPyObject() item = Qitem.data(Qt.UserRole)
self.edit_format.setCurrentIndex(self.edit_format.findText(item[0])) self.edit_format.setCurrentIndex(self.edit_format.findText(item[0]))
self.edit_device.setCurrentIndex(self.edit_device.findText(item[1])) self.edit_device.setCurrentIndex(self.edit_device.findText(item[1]))

View File

@ -141,7 +141,7 @@ class ConfigWidget(ConfigWidgetBase, Ui_Form):
_('The search term cannot be blank'), _('The search term cannot be blank'),
show=True) show=True)
if idx != 0: if idx != 0:
orig_name = unicode(self.gst_names.itemData(idx).toString()) orig_name = unicode(self.gst_names.itemData(idx) or '')
else: else:
orig_name = '' orig_name = ''
if name != orig_name: if name != orig_name:
@ -206,7 +206,7 @@ class ConfigWidget(ConfigWidgetBase, Ui_Form):
if idx == 0: if idx == 0:
self.gst_value.setText('') self.gst_value.setText('')
else: else:
name = unicode(self.gst_names.itemData(idx).toString()) name = unicode(self.gst_names.itemData(idx) or '')
self.gst_value.setText(','.join(self.gst[name])) self.gst_value.setText(','.join(self.gst[name]))
self.gst_value.blockSignals(False) self.gst_value.blockSignals(False)

View File

@ -81,7 +81,7 @@ class TextureChooser(QDialog):
self.update_remove_state() self.update_remove_state()
if initial: if initial:
existing = {unicode(i.data(Qt.UserRole).toString()):i for i in (self.images.item(c) for c in xrange(self.images.count()))} existing = {unicode(i.data(Qt.UserRole) or ''):i for i in (self.images.item(c) for c in xrange(self.images.count()))}
item = existing.get(initial, None) item = existing.get(initial, None)
if item is not None: if item is not None:
item.setSelected(True) item.setSelected(True)
@ -112,7 +112,7 @@ class TextureChooser(QDialog):
path = path[0] path = path[0]
fname = os.path.basename(path) fname = os.path.basename(path)
name = fname.rpartition('.')[0] name = fname.rpartition('.')[0]
existing = {unicode(i.data(Qt.UserRole).toString()):i for i in (self.images.item(c) for c in xrange(self.images.count()))} existing = {unicode(i.data(Qt.UserRole) or ''):i for i in (self.images.item(c) for c in xrange(self.images.count()))}
dest = os.path.join(self.tdir, fname) dest = os.path.join(self.tdir, fname)
with open(path, 'rb') as s, open(dest, 'wb') as f: with open(path, 'rb') as s, open(dest, 'wb') as f:
shutil.copyfileobj(s, f) shutil.copyfileobj(s, f)
@ -131,7 +131,7 @@ class TextureChooser(QDialog):
@property @property
def selected_fname(self): def selected_fname(self):
try: try:
return unicode(self.selected_item.data(Qt.UserRole).toString()) return unicode(self.selected_item.data(Qt.UserRole) or '')
except (AttributeError, TypeError): except (AttributeError, TypeError):
pass pass
@ -141,7 +141,7 @@ class TextureChooser(QDialog):
if self.selected_fname.startswith(':'): if self.selected_fname.startswith(':'):
return error_dialog(self, _('Cannot remove'), return error_dialog(self, _('Cannot remove'),
_('Cannot remover builtin textures'), show=True) _('Cannot remover builtin textures'), show=True)
os.remove(unicode(self.selected_item.data(Qt.UserRole+1).toString())) os.remove(unicode(self.selected_item.data(Qt.UserRole+1) or ''))
self.images.takeItem(self.images.row(self.selected_item)) self.images.takeItem(self.images.row(self.selected_item))
if __name__ == '__main__': if __name__ == '__main__':

View File

@ -8,10 +8,10 @@ __docformat__ = 'restructuredtext en'
from functools import partial from functools import partial
from PyQt5.Qt import QAbstractListModel, Qt, QIcon, \ from PyQt5.Qt import QAbstractListModel, Qt, QIcon, \
QVariant, QItemSelectionModel QItemSelectionModel
from calibre.gui2.preferences.toolbar_ui import Ui_Form from calibre.gui2.preferences.toolbar_ui import Ui_Form
from calibre.gui2 import gprefs, NONE, warning_dialog from calibre.gui2 import gprefs, warning_dialog
from calibre.gui2.preferences import ConfigWidgetBase, test_widget from calibre.gui2.preferences import ConfigWidgetBase, test_widget
@ -58,19 +58,19 @@ class BaseModel(QAbstractListModel):
text = text.replace('&', '') text = text.replace('&', '')
if text == _('%d books'): if text == _('%d books'):
text = _('Choose library') text = _('Choose library')
return QVariant(text) return (text)
if role == Qt.DecorationRole: if role == Qt.DecorationRole:
if hasattr(self._data[row], 'qaction'): if hasattr(self._data[row], 'qaction'):
icon = self._data[row].qaction.icon() icon = self._data[row].qaction.icon()
if not icon.isNull(): if not icon.isNull():
return QVariant(icon) return (icon)
ic = action[1] ic = action[1]
if ic is None: if ic is None:
ic = 'blank.png' ic = 'blank.png'
return QVariant(QIcon(I(ic))) return (QIcon(I(ic)))
if role == Qt.ToolTipRole and action[2] is not None: if role == Qt.ToolTipRole and action[2] is not None:
return QVariant(action[2]) return (action[2])
return NONE return None
def names(self, indexes): def names(self, indexes):
rows = [i.row() for i in indexes] rows = [i.row() for i in indexes]
@ -110,7 +110,8 @@ class AllModel(BaseModel):
def add(self, names): def add(self, names):
actions = [] actions = []
for name in names: for name in names:
if name is None or name.startswith('---'): continue if name is None or name.startswith('---'):
continue
actions.append(self.name_to_action(name, self.gui)) actions.append(self.name_to_action(name, self.gui))
self.beginResetModel() self.beginResetModel()
self._data.extend(actions) self._data.extend(actions)
@ -122,7 +123,8 @@ class AllModel(BaseModel):
remove = set([]) remove = set([])
for row in rows: for row in rows:
ac = self._data[row] ac = self._data[row]
if ac.name.startswith('---'): continue if ac.name.startswith('---'):
continue
if ac.name in allowed: if ac.name in allowed:
remove.add(row) remove.add(row)
ndata = [] ndata = []
@ -260,15 +262,15 @@ class ConfigWidget(ConfigWidgetBase, Ui_Form):
self.current_actions.entered.connect(self.current_entered) self.current_actions.entered.connect(self.current_entered)
def all_entered(self, index): def all_entered(self, index):
tt = self.all_actions.model().data(index, Qt.ToolTipRole).toString() tt = self.all_actions.model().data(index, Qt.ToolTipRole) or ''
self.help_text.setText(tt) self.help_text.setText(tt)
def current_entered(self, index): def current_entered(self, index):
tt = self.current_actions.model().data(index, Qt.ToolTipRole).toString() tt = self.current_actions.model().data(index, Qt.ToolTipRole) or ''
self.help_text.setText(tt) self.help_text.setText(tt)
def what_changed(self, idx): def what_changed(self, idx):
key = unicode(self.what.itemData(idx).toString()) key = unicode(self.what.itemData(idx) or '')
if key == 'blank': if key == 'blank':
self.actions_widget.setVisible(False) self.actions_widget.setVisible(False)
self.spacer_widget.setVisible(True) self.spacer_widget.setVisible(True)
@ -358,4 +360,3 @@ if __name__ == '__main__':
from PyQt5.Qt import QApplication from PyQt5.Qt import QApplication
app = QApplication([]) app = QApplication([])
test_widget('Interface', 'Toolbar') test_widget('Interface', 'Toolbar')

View File

@ -11,7 +11,7 @@ from collections import OrderedDict
from calibre.gui2.preferences import ConfigWidgetBase, test_widget, AbortCommit from calibre.gui2.preferences import ConfigWidgetBase, test_widget, AbortCommit
from calibre.gui2.preferences.tweaks_ui import Ui_Form from calibre.gui2.preferences.tweaks_ui import Ui_Form
from calibre.gui2 import error_dialog, NONE, info_dialog from calibre.gui2 import error_dialog, info_dialog
from calibre.utils.config import read_raw_tweaks, write_tweaks from calibre.utils.config import read_raw_tweaks, write_tweaks
from calibre.gui2.widgets import PythonHighlighter from calibre.gui2.widgets import PythonHighlighter
from calibre import isbytestring from calibre import isbytestring
@ -115,7 +115,7 @@ class Tweaks(QAbstractListModel, SearchQueryParser): # {{{
try: try:
tweak = self.tweaks[row] tweak = self.tweaks[row]
except: except:
return NONE return None
if role == Qt.DisplayRole: if role == Qt.DisplayRole:
return textwrap.fill(tweak.name, 40) return textwrap.fill(tweak.name, 40)
if role == Qt.FontRole and tweak.is_customized: if role == Qt.FontRole and tweak.is_customized:
@ -132,7 +132,7 @@ class Tweaks(QAbstractListModel, SearchQueryParser): # {{{
return textwrap.fill(tt) return textwrap.fill(tt)
if role == Qt.UserRole: if role == Qt.UserRole:
return tweak return tweak
return NONE return None
def parse_tweaks(self, defaults, custom): def parse_tweaks(self, defaults, custom):
l, g = {}, {} l, g = {}, {}
@ -195,7 +195,7 @@ class Tweaks(QAbstractListModel, SearchQueryParser): # {{{
def restore_to_default(self, idx): def restore_to_default(self, idx):
tweak = self.data(idx, Qt.UserRole) tweak = self.data(idx, Qt.UserRole)
if tweak is not NONE: if tweak is not None:
tweak.restore_to_default() tweak.restore_to_default()
self.dataChanged.emit(idx, idx) self.dataChanged.emit(idx, idx)
@ -206,7 +206,7 @@ class Tweaks(QAbstractListModel, SearchQueryParser): # {{{
def update_tweak(self, idx, varmap): def update_tweak(self, idx, varmap):
tweak = self.data(idx, Qt.UserRole) tweak = self.data(idx, Qt.UserRole)
if tweak is not NONE: if tweak is not None:
tweak.update(varmap) tweak.update(varmap)
self.dataChanged.emit(idx, idx) self.dataChanged.emit(idx, idx)