Remove qt_ prefix from qtutils functions.

This commit is contained in:
Florian Bruhin 2014-08-26 19:23:06 +02:00
parent d625cde28c
commit e04b31eb90
22 changed files with 67 additions and 67 deletions

View File

@ -244,7 +244,7 @@ instead of using exceptions.
+ +
If a function gets or returns a Qt object which If a function gets or returns a Qt object which
has an `.isValid()` method such as `QUrl` or `QModelIndex`, there's a helper has an `.isValid()` method such as `QUrl` or `QModelIndex`, there's a helper
function `qt_ensure_valid` in `qutebrowser.utils.qt` which should get called on function `ensure_valid` in `qutebrowser.utils.qt` which should get called on
all such objects. It will raise `qutebrowser.utils.qt.QtValueError` if the all such objects. It will raise `qutebrowser.utils.qt.QtValueError` if the
value is not valid. value is not valid.
+ +
@ -372,8 +372,8 @@ displaying it to the user.
* Name a string URL something like `urlstr`, and a `QUrl` something like `url`. * Name a string URL something like `urlstr`, and a `QUrl` something like `url`.
* Mention in the docstring whether your function needs a URL string or a * Mention in the docstring whether your function needs a URL string or a
`QUrl`. `QUrl`.
* Call `qt_ensure_valid` from `utils.qt` whenever getting or creating a * Call `ensure_valid` from `utils.qt` whenever getting or creating a `QUrl` and
`QUrl` and take appropriate action if not. take appropriate action if not.
Style conventions Style conventions

View File

@ -86,7 +86,7 @@ class Application(QApplication):
# We don't enable this earlier because some imports trigger # We don't enable this earlier because some imports trigger
# warnings (which are not our fault). # warnings (which are not our fault).
warnings.simplefilter('default') warnings.simplefilter('default')
qt_args = qtutils.get_qt_args(args) qt_args = qtutils.get_args(args)
log.init.debug("Qt arguments: {}, based on {}".format(qt_args, args)) log.init.debug("Qt arguments: {}, based on {}".format(qt_args, args))
super().__init__(qt_args) super().__init__(qt_args)
self._quit_status = { self._quit_status = {

View File

@ -347,7 +347,7 @@ class DownloadManager(QObject):
url: The URL to get, as QUrl url: The URL to get, as QUrl
page: The QWebPage to get the download from. page: The QWebPage to get the download from.
""" """
qtutils.qt_ensure_valid(url) qtutils.ensure_valid(url)
req = QNetworkRequest(url) req = QNetworkRequest(url)
reply = page.networkAccessManager().get(req) reply = page.networkAccessManager().get(req)
self.fetch(reply) self.fetch(reply)

View File

@ -340,7 +340,7 @@ class HintManager(QObject):
Args: Args:
url: The URL to open as a QURL. url: The URL to open as a QURL.
""" """
qtutils.qt_ensure_valid(url) qtutils.ensure_valid(url)
sel = self._context.target == Target.yank_primary sel = self._context.target == Target.yank_primary
mode = QClipboard.Selection if sel else QClipboard.Clipboard mode = QClipboard.Selection if sel else QClipboard.Clipboard
urlstr = url.toString(QUrl.FullyEncoded | QUrl.RemovePassword) urlstr = url.toString(QUrl.FullyEncoded | QUrl.RemovePassword)
@ -354,7 +354,7 @@ class HintManager(QObject):
Args: Args:
url: The URL to open as a QUrl. url: The URL to open as a QUrl.
""" """
qtutils.qt_ensure_valid(url) qtutils.ensure_valid(url)
urlstr = url.toDisplayString(QUrl.FullyEncoded) urlstr = url.toDisplayString(QUrl.FullyEncoded)
args = self._context.get_args(urlstr) args = self._context.get_args(urlstr)
message.set_cmd_text(' '.join(args)) message.set_cmd_text(' '.join(args))
@ -370,19 +370,19 @@ class HintManager(QObject):
message.error("No suitable link found for this element.", message.error("No suitable link found for this element.",
immediately=True) immediately=True)
return return
qtutils.qt_ensure_valid(url) qtutils.ensure_valid(url)
self.download_get.emit(url, elem.webFrame().page()) self.download_get.emit(url, elem.webFrame().page())
def _call_userscript(self, url): def _call_userscript(self, url):
"""Call an userscript from a hint.""" """Call an userscript from a hint."""
qtutils.qt_ensure_valid(url) qtutils.ensure_valid(url)
cmd = self._context.args[0] cmd = self._context.args[0]
args = self._context.args[1:] args = self._context.args[1:]
userscripts.run(cmd, *args, url=url) userscripts.run(cmd, *args, url=url)
def _spawn(self, url): def _spawn(self, url):
"""Spawn a simple command from a hint.""" """Spawn a simple command from a hint."""
qtutils.qt_ensure_valid(url) qtutils.ensure_valid(url)
urlstr = url.toString(QUrl.FullyEncoded | QUrl.RemovePassword) urlstr = url.toString(QUrl.FullyEncoded | QUrl.RemovePassword)
args = self._context.get_args(urlstr) args = self._context.get_args(urlstr)
subprocess.Popen(args) subprocess.Popen(args)
@ -406,7 +406,7 @@ class HintManager(QObject):
url = QUrl(text) url = QUrl(text)
if url.isRelative(): if url.isRelative():
url = baseurl.resolved(url) url = baseurl.resolved(url)
qtutils.qt_ensure_valid(url) qtutils.ensure_valid(url)
return url return url
def _find_prevnext(self, frame, prev=False): def _find_prevnext(self, frame, prev=False):

View File

@ -67,7 +67,7 @@ def prompt_save(url):
Args: Args:
url: The quickmark url as a QUrl. url: The quickmark url as a QUrl.
""" """
qtutils.qt_ensure_valid(url) qtutils.ensure_valid(url)
urlstr = url.toString(QUrl.RemovePassword | QUrl.FullyEncoded) urlstr = url.toString(QUrl.RemovePassword | QUrl.FullyEncoded)
message.ask_async("Add quickmark:", usertypes.PromptMode.text, message.ask_async("Add quickmark:", usertypes.PromptMode.text,
functools.partial(quickmark_add, urlstr)) functools.partial(quickmark_add, urlstr))

View File

@ -74,7 +74,7 @@ class BaseCompletionModel(QStandardItemModel):
index: A QModelIndex of the item to mark. index: A QModelIndex of the item to mark.
needle: The string to mark. needle: The string to mark.
""" """
qtutils.qt_ensure_valid(index) qtutils.ensure_valid(index)
haystack = self.data(index) haystack = self.data(index)
marks = self._get_marks(needle, haystack) marks = self._get_marks(needle, haystack)
ok = self.setData(index, marks, Role.marks) ok = self.setData(index, marks, Role.marks)
@ -132,7 +132,7 @@ class BaseCompletionModel(QStandardItemModel):
Return: Return:
The item flags, or Qt.NoItemFlags on error. The item flags, or Qt.NoItemFlags on error.
""" """
qtutils.qt_ensure_valid(index) qtutils.ensure_valid(index)
if index.parent().isValid(): if index.parent().isValid():
# item # item
return Qt.ItemIsEnabled | Qt.ItemIsSelectable return Qt.ItemIsEnabled | Qt.ItemIsSelectable

View File

@ -87,7 +87,7 @@ class SettingOptionCompletionModel(basecompletion.BaseCompletionModel):
return return
val = config.get(section, option, raw=True) val = config.get(section, option, raw=True)
idx = item.index() idx = item.index()
qtutils.qt_ensure_valid(idx) qtutils.ensure_valid(idx)
ok = self.setData(idx, val, Qt.DisplayRole) ok = self.setData(idx, val, Qt.DisplayRole)
if not ok: if not ok:
raise ValueError("Setting data failed! (section: {}, option: {}, " raise ValueError("Setting data failed! (section: {}, option: {}, "
@ -138,7 +138,7 @@ class SettingValueCompletionModel(basecompletion.BaseCompletionModel):
if not value: if not value:
value = '""' value = '""'
idx = self.cur_item.index() idx = self.cur_item.index()
qtutils.qt_ensure_valid(idx) qtutils.ensure_valid(idx)
ok = self.setData(idx, value, Qt.DisplayRole) ok = self.setData(idx, value, Qt.DisplayRole)
if not ok: if not ok:
raise ValueError("Setting data failed! (section: {}, option: {}, " raise ValueError("Setting data failed! (section: {}, option: {}, "

View File

@ -81,7 +81,7 @@ class CompletionFilterModel(QSortFilterProxyModel):
count = 0 count = 0
for i in range(self.rowCount()): for i in range(self.rowCount()):
cat = self.index(i, 0) cat = self.index(i, 0)
qtutils.qt_ensure_valid(cat) qtutils.ensure_valid(cat)
count += self.rowCount(cat) count += self.rowCount(cat)
return count return count
@ -89,10 +89,10 @@ class CompletionFilterModel(QSortFilterProxyModel):
"""Return the first item in the model.""" """Return the first item in the model."""
for i in range(self.rowCount()): for i in range(self.rowCount()):
cat = self.index(i, 0) cat = self.index(i, 0)
qtutils.qt_ensure_valid(cat) qtutils.ensure_valid(cat)
if cat.model().hasChildren(cat): if cat.model().hasChildren(cat):
index = self.index(0, 0, cat) index = self.index(0, 0, cat)
qtutils.qt_ensure_valid(index) qtutils.ensure_valid(index)
return index return index
return QModelIndex() return QModelIndex()
@ -100,10 +100,10 @@ class CompletionFilterModel(QSortFilterProxyModel):
"""Return the last item in the model.""" """Return the last item in the model."""
for i in range(self.rowCount() - 1, -1, -1): for i in range(self.rowCount() - 1, -1, -1):
cat = self.index(i, 0) cat = self.index(i, 0)
qtutils.qt_ensure_valid(cat) qtutils.ensure_valid(cat)
if cat.model().hasChildren(cat): if cat.model().hasChildren(cat):
index = self.index(self.rowCount(cat) - 1, 0, cat) index = self.index(self.rowCount(cat) - 1, 0, cat)
qtutils.qt_ensure_valid(index) qtutils.ensure_valid(index)
return index return index
return QModelIndex() return QModelIndex()
@ -111,12 +111,12 @@ class CompletionFilterModel(QSortFilterProxyModel):
"""Mark the given text in all visible items.""" """Mark the given text in all visible items."""
for i in range(self.rowCount()): for i in range(self.rowCount()):
cat = self.index(i, 0) cat = self.index(i, 0)
qtutils.qt_ensure_valid(cat) qtutils.ensure_valid(cat)
for k in range(self.rowCount(cat)): for k in range(self.rowCount(cat)):
index = self.index(k, 0, cat) index = self.index(k, 0, cat)
qtutils.qt_ensure_valid(index) qtutils.ensure_valid(index)
index = self.mapToSource(index) index = self.mapToSource(index)
qtutils.qt_ensure_valid(index) qtutils.ensure_valid(index)
self.srcmodel.mark_item(index, text) self.srcmodel.mark_item(index, text)
def setSourceModel(self, model): def setSourceModel(self, model):
@ -142,7 +142,7 @@ class CompletionFilterModel(QSortFilterProxyModel):
if parent == QModelIndex(): if parent == QModelIndex():
return True return True
idx = self.srcmodel.index(row, 0, parent) idx = self.srcmodel.index(row, 0, parent)
qtutils.qt_ensure_valid(idx) qtutils.ensure_valid(idx)
data = self.srcmodel.data(idx) data = self.srcmodel.data(idx)
# TODO more sophisticated filtering # TODO more sophisticated filtering
if not self.pattern: if not self.pattern:
@ -162,8 +162,8 @@ class CompletionFilterModel(QSortFilterProxyModel):
Return: Return:
True if left < right, else False True if left < right, else False
""" """
qtutils.qt_ensure_valid(lindex) qtutils.ensure_valid(lindex)
qtutils.qt_ensure_valid(rindex) qtutils.ensure_valid(rindex)
left_sort = self.srcmodel.data(lindex, role=completion.Role.sort) left_sort = self.srcmodel.data(lindex, role=completion.Role.sort)
right_sort = self.srcmodel.data(rindex, role=completion.Role.sort) right_sort = self.srcmodel.data(rindex, role=completion.Role.sort)

View File

@ -57,7 +57,7 @@ class DownloadModel(QAbstractListModel):
def on_data_changed(self, idx): def on_data_changed(self, idx):
"""Update view when DownloadManager data changed.""" """Update view when DownloadManager data changed."""
model_idx = self.index(idx, 0) model_idx = self.index(idx, 0)
qtutils.qt_ensure_valid(model_idx) qtutils.ensure_valid(model_idx)
self.dataChanged.emit(model_idx, model_idx) self.dataChanged.emit(model_idx, model_idx)
def last_index(self): def last_index(self):
@ -79,7 +79,7 @@ class DownloadModel(QAbstractListModel):
def data(self, index, role): def data(self, index, role):
"""Download data from DownloadManager.""" """Download data from DownloadManager."""
qtutils.qt_ensure_valid(index) qtutils.ensure_valid(index)
if index.parent().isValid() or index.column() != 0: if index.parent().isValid() or index.column() != 0:
return QVariant() return QVariant()

View File

@ -72,7 +72,7 @@ def get_argparser():
action='store_true') action='store_true')
# For the Qt args, we use store_const with const=True rather than # For the Qt args, we use store_const with const=True rather than
# store_true because we want the default to be None, to make # store_true because we want the default to be None, to make
# utils.qt:get_qt_args easier. # utils.qt:get_args easier.
debug.add_argument('--qt-style', help="Set the Qt GUI style to use.", debug.add_argument('--qt-style', help="Set the Qt GUI style to use.",
metavar='STYLE') metavar='STYLE')
debug.add_argument('--qt-stylesheet', help="Override the Qt application " debug.add_argument('--qt-stylesheet', help="Override the Qt application "

View File

@ -84,7 +84,7 @@ class CheckOverflowTests(unittest.TestCase):
class GetQtArgsTests(unittest.TestCase): class GetQtArgsTests(unittest.TestCase):
"""Tests for get_qt_args.""" """Tests for get_args."""
def setUp(self): def setUp(self):
self.parser = argparse.ArgumentParser() self.parser = argparse.ArgumentParser()
@ -109,26 +109,26 @@ class GetQtArgsTests(unittest.TestCase):
def test_no_qt_args(self): def test_no_qt_args(self):
"""Test commandline with no Qt arguments given.""" """Test commandline with no Qt arguments given."""
ns = self._namespace(['--foo'], flags=['--foo']) ns = self._namespace(['--foo'], flags=['--foo'])
self.assertEqual(qt.get_qt_args(ns), [sys.argv[0]]) self.assertEqual(qt.get_args(ns), [sys.argv[0]])
def test_qt_flag(self): def test_qt_flag(self):
"""Test commandline with a Qt flag.""" """Test commandline with a Qt flag."""
ns = self._namespace(['--foo', '--qt-reverse', '--bar'], ns = self._namespace(['--foo', '--qt-reverse', '--bar'],
flags=['--foo', '--qt-reverse', '--bar']) flags=['--foo', '--qt-reverse', '--bar'])
self.assertEqual(qt.get_qt_args(ns), [sys.argv[0], '-reverse']) self.assertEqual(qt.get_args(ns), [sys.argv[0], '-reverse'])
def test_qt_arg(self): def test_qt_arg(self):
"""Test commandline with a Qt argument.""" """Test commandline with a Qt argument."""
ns = self._namespace(['--qt-stylesheet', 'foobar'], ns = self._namespace(['--qt-stylesheet', 'foobar'],
args=['--qt-stylesheet']) args=['--qt-stylesheet'])
self.assertEqual(qt.get_qt_args(ns), [sys.argv[0], '-stylesheet', self.assertEqual(qt.get_args(ns), [sys.argv[0], '-stylesheet',
'foobar']) 'foobar'])
def test_qt_both(self): def test_qt_both(self):
"""Test commandline with a Qt argument and flag.""" """Test commandline with a Qt argument and flag."""
ns = self._namespace(['--qt-stylesheet', 'foobar', '--qt-reverse'], ns = self._namespace(['--qt-stylesheet', 'foobar', '--qt-reverse'],
flags=['--qt-reverse'], args=['--qt-stylesheet']) flags=['--qt-reverse'], args=['--qt-stylesheet'])
qt_args = qt.get_qt_args(ns) qt_args = qt.get_args(ns)
self.assertEqual(qt_args[0], sys.argv[0]) self.assertEqual(qt_args[0], sys.argv[0])
self.assertIn('-reverse', qt_args) self.assertIn('-reverse', qt_args)
self.assertIn('-stylesheet', qt_args) self.assertIn('-stylesheet', qt_args)

View File

@ -204,8 +204,8 @@ def check_qt_version():
"""Check if the Qt version is recent enough.""" """Check if the Qt version is recent enough."""
import operator import operator
from PyQt5.QtCore import qVersion from PyQt5.QtCore import qVersion
from qutebrowser.utils.qt import qt_version_check from qutebrowser.utils import qt as qtutils
if qt_version_check('5.2.0', operator.lt): if qtutils.version_check('5.2.0', operator.lt):
text = ("Fatal error: Qt and PyQt >= 5.2.0 are required, but {} is " text = ("Fatal error: Qt and PyQt >= 5.2.0 are required, but {} is "
"installed.".format(qVersion())) "installed.".format(qVersion()))
_die(text, exception=False) _die(text, exception=False)

View File

@ -190,7 +190,7 @@ def actute_warning():
return return
# Qt >= 5.3 doesn't seem to be affected # Qt >= 5.3 doesn't seem to be affected
try: try:
if qtutils.qt_version_check('5.3.0'): if qtutils.version_check('5.3.0'):
return return
except ValueError: except ValueError:
pass pass
@ -247,8 +247,8 @@ def interpolate_color(start, end, percent, colorspace=QColor.Rgb):
Raise: Raise:
ValueError if invalid parameters are passed. ValueError if invalid parameters are passed.
""" """
qtutils.qt_ensure_valid(start) qtutils.ensure_valid(start)
qtutils.qt_ensure_valid(end) qtutils.ensure_valid(end)
out = QColor() out = QColor()
if colorspace == QColor.Rgb: if colorspace == QColor.Rgb:
a_c1, a_c2, a_c3, _alpha = start.getRgb() a_c1, a_c2, a_c3, _alpha = start.getRgb()
@ -271,7 +271,7 @@ def interpolate_color(start, end, percent, colorspace=QColor.Rgb):
else: else:
raise ValueError("Invalid colorspace!") raise ValueError("Invalid colorspace!")
out = out.convertTo(start.spec()) out = out.convertTo(start.spec())
qtutils.qt_ensure_valid(out) qtutils.ensure_valid(out)
return out return out

View File

@ -46,7 +46,7 @@ MINVALS = {
} }
def qt_version_check(version, op=operator.ge): def version_check(version, op=operator.ge):
"""Check if the Qt runtime version is the version supplied or newer. """Check if the Qt runtime version is the version supplied or newer.
Args: Args:
@ -88,7 +88,7 @@ def check_overflow(arg, ctype, fatal=True):
return arg return arg
def get_qt_args(namespace): def get_args(namespace):
"""Get the Qt QApplication arguments based on an argparse namespace. """Get the Qt QApplication arguments based on an argparse namespace.
Args: Args:
@ -114,10 +114,10 @@ def get_qt_args(namespace):
def check_print_compat(): def check_print_compat():
"""Check if printing should work in the given Qt version.""" """Check if printing should work in the given Qt version."""
return not (os.name == 'nt' and qt_version_check('5.3.0', operator.lt)) return not (os.name == 'nt' and version_check('5.3.0', operator.lt))
def qt_ensure_valid(obj): def ensure_valid(obj):
"""Ensure a Qt object with an .isValid() method is valid. """Ensure a Qt object with an .isValid() method is valid.
Raise: Raise:
@ -129,7 +129,7 @@ def qt_ensure_valid(obj):
class QtValueError(ValueError): class QtValueError(ValueError):
"""Exception which gets raised by qt_ensure_valid.""" """Exception which gets raised by ensure_valid."""
def __init__(self, obj): def __init__(self, obj):
try: try:

View File

@ -65,7 +65,7 @@ def _get_search_url(txt):
if not term: if not term:
raise FuzzyUrlError("No search term given") raise FuzzyUrlError("No search term given")
url = QUrl.fromUserInput(template.format(urllib.parse.quote(term))) url = QUrl.fromUserInput(template.format(urllib.parse.quote(term)))
qtutils.qt_ensure_valid(url) qtutils.ensure_valid(url)
return url return url
@ -143,7 +143,7 @@ def fuzzy_url(urlstr):
url = QUrl.fromUserInput(stripped) url = QUrl.fromUserInput(stripped)
logger.debug("Converting fuzzy term {} to URL -> {}".format( logger.debug("Converting fuzzy term {} to URL -> {}".format(
urlstr, url.toDisplayString())) urlstr, url.toDisplayString()))
qtutils.qt_ensure_valid(url) qtutils.ensure_valid(url)
return url return url

View File

@ -167,7 +167,7 @@ class CompletionView(QTreeView):
# No completion running at the moment, ignore keypress # No completion running at the moment, ignore keypress
return return
idx = self._next_idx(prev) idx = self._next_idx(prev)
qtutils.qt_ensure_valid(idx) qtutils.ensure_valid(idx)
self.selectionModel().setCurrentIndex( self.selectionModel().setCurrentIndex(
idx, QItemSelectionModel.ClearAndSelect | idx, QItemSelectionModel.ClearAndSelect |
QItemSelectionModel.Rows) QItemSelectionModel.Rows)

View File

@ -98,12 +98,12 @@ class CompletionItemDelegate(QStyledItemDelegate):
text_rect_ = self._style.subElementRect( text_rect_ = self._style.subElementRect(
self._style.SE_ItemViewItemText, self._opt, self._opt.widget) self._style.SE_ItemViewItemText, self._opt, self._opt.widget)
qtutils.qt_ensure_valid(text_rect_) qtutils.ensure_valid(text_rect_)
margin = self._style.pixelMetric(QStyle.PM_FocusFrameHMargin, margin = self._style.pixelMetric(QStyle.PM_FocusFrameHMargin,
self._opt, self._opt.widget) + 1 self._opt, self._opt.widget) + 1
# remove width padding # remove width padding
text_rect = text_rect_.adjusted(margin, 0, -margin, 0) text_rect = text_rect_.adjusted(margin, 0, -margin, 0)
qtutils.qt_ensure_valid(text_rect) qtutils.ensure_valid(text_rect)
# move text upwards a bit # move text upwards a bit
if index.parent().isValid(): if index.parent().isValid():
text_rect.adjust(0, -1, 0, -1) text_rect.adjust(0, -1, 0, -1)
@ -217,7 +217,7 @@ class CompletionItemDelegate(QStyledItemDelegate):
o.rect = self._style.subElementRect( o.rect = self._style.subElementRect(
self._style.SE_ItemViewItemFocusRect, self._opt, self._opt.widget) self._style.SE_ItemViewItemFocusRect, self._opt, self._opt.widget)
o.state |= QStyle.State_KeyboardFocusChange | QStyle.State_Item o.state |= QStyle.State_KeyboardFocusChange | QStyle.State_Item
qtutils.qt_ensure_valid(o.rect) qtutils.ensure_valid(o.rect)
if state & QStyle.State_Enabled: if state & QStyle.State_Enabled:
cg = QPalette.Normal cg = QPalette.Normal
else: else:
@ -253,7 +253,7 @@ class CompletionItemDelegate(QStyledItemDelegate):
docsize = self._doc.size().toSize() docsize = self._doc.size().toSize()
size = self._style.sizeFromContents(QStyle.CT_ItemViewItem, self._opt, size = self._style.sizeFromContents(QStyle.CT_ItemViewItem, self._opt,
docsize, self._opt.widget) docsize, self._opt.widget)
qtutils.qt_ensure_valid(size) qtutils.ensure_valid(size)
return size + QSize(10, 3) return size + QSize(10, 3)
def paint(self, painter, option, index): def paint(self, painter, option, index):

View File

@ -91,5 +91,5 @@ class DownloadView(QListView):
size = QSize(0, height + 2) size = QSize(0, height + 2)
else: else:
size = QSize(0, 0) size = QSize(0, 0)
qtutils.qt_ensure_valid(size) qtutils.ensure_valid(size)
return size return size

View File

@ -79,7 +79,7 @@ class TextBase(QLabel):
"""Extend QLabel::resizeEvent to update the elided text afterwards.""" """Extend QLabel::resizeEvent to update the elided text afterwards."""
super().resizeEvent(e) super().resizeEvent(e)
size = e.size() size = e.size()
qtutils.qt_ensure_valid(size) qtutils.ensure_valid(size)
self._update_elided_text(size.width()) self._update_elided_text(size.width())
def paintEvent(self, e): def paintEvent(self, e):
@ -90,6 +90,6 @@ class TextBase(QLabel):
e.accept() e.accept()
painter = QPainter(self) painter = QPainter(self)
geom = self.geometry() geom = self.geometry()
qtutils.qt_ensure_valid(geom) qtutils.ensure_valid(geom)
painter.drawText(0, 0, geom.width(), geom.height(), painter.drawText(0, 0, geom.width(), geom.height(),
self.alignment(), self._elided_text) self.alignment(), self._elided_text)

View File

@ -210,7 +210,7 @@ class TabbedBrowser(tabwidget.TabWidget):
""" """
url = self.currentWidget().cur_url url = self.currentWidget().cur_url
try: try:
qtutils.qt_ensure_valid(url) qtutils.ensure_valid(url)
except qtutils.QtValueError as e: except qtutils.QtValueError as e:
msg = "Current URL is invalid" msg = "Current URL is invalid"
if e.reason: if e.reason:
@ -266,7 +266,7 @@ class TabbedBrowser(tabwidget.TabWidget):
if tab is self.last_focused: if tab is self.last_focused:
self.last_focused = None self.last_focused = None
if not tab.cur_url.isEmpty(): if not tab.cur_url.isEmpty():
qtutils.qt_ensure_valid(tab.cur_url) qtutils.ensure_valid(tab.cur_url)
self.url_stack.append(tab.cur_url) self.url_stack.append(tab.cur_url)
tab.shutdown() tab.shutdown()
self._tabs.remove(tab) self._tabs.remove(tab)
@ -281,7 +281,7 @@ class TabbedBrowser(tabwidget.TabWidget):
url: The URL to open as QUrl. url: The URL to open as QUrl.
newtab: True to open URL in a new tab, False otherwise. newtab: True to open URL in a new tab, False otherwise.
""" """
qtutils.qt_ensure_valid(url) qtutils.ensure_valid(url)
if newtab: if newtab:
self.tabopen(url, background=False) self.tabopen(url, background=False)
else: else:
@ -324,7 +324,7 @@ class TabbedBrowser(tabwidget.TabWidget):
The opened WebView instance. The opened WebView instance.
""" """
if url is not None: if url is not None:
qtutils.qt_ensure_valid(url) qtutils.ensure_valid(url)
log.webview.debug("Creating new tab with URL {}".format(url)) log.webview.debug("Creating new tab with URL {}".format(url))
tab = webview.WebView(self) tab = webview.WebView(self)
self._connect_tab_signals(tab) self._connect_tab_signals(tab)

View File

@ -211,7 +211,7 @@ class TabBar(QTabBar):
# If we *do* have enough space, tabs should occupy the whole window # If we *do* have enough space, tabs should occupy the whole window
# width. # width.
size = QSize(self.width() / self.count(), height) size = QSize(self.width() / self.count(), height)
qtutils.qt_ensure_valid(size) qtutils.ensure_valid(size)
return size return size
def paintEvent(self, _e): def paintEvent(self, _e):
@ -311,7 +311,7 @@ class TabBarStyle(QCommonStyle):
elif element == QStyle.CE_TabBarTabLabel: elif element == QStyle.CE_TabBarTabLabel:
text_rect, icon_rect = self._tab_layout(opt) text_rect, icon_rect = self._tab_layout(opt)
if not opt.icon.isNull(): if not opt.icon.isNull():
qtutils.qt_ensure_valid(icon_rect) qtutils.ensure_valid(icon_rect)
icon_mode = (QIcon.Normal if opt.state & QStyle.State_Enabled icon_mode = (QIcon.Normal if opt.state & QStyle.State_Enabled
else QIcon.Disabled) else QIcon.Disabled)
icon_state = (QIcon.On if opt.state & QStyle.State_Selected icon_state = (QIcon.On if opt.state & QStyle.State_Selected
@ -382,7 +382,7 @@ class TabBarStyle(QCommonStyle):
padding = self.pixelMetric(PM_TabBarPadding, opt) padding = self.pixelMetric(PM_TabBarPadding, opt)
icon_rect = QRect() icon_rect = QRect()
text_rect = QRect(opt.rect) text_rect = QRect(opt.rect)
qtutils.qt_ensure_valid(text_rect) qtutils.ensure_valid(text_rect)
indicator_width = config.get('tabs', 'indicator-width') indicator_width = config.get('tabs', 'indicator-width')
text_rect.adjust(padding, 0, 0, 0) text_rect.adjust(padding, 0, 0, 0)
if indicator_width != 0: if indicator_width != 0:
@ -419,5 +419,5 @@ class TabBarStyle(QCommonStyle):
text_rect.center().y() - tab_icon_size.height() / 2, text_rect.center().y() - tab_icon_size.height() / 2,
tab_icon_size.width(), tab_icon_size.height()) tab_icon_size.width(), tab_icon_size.height())
icon_rect = self._style.visualRect(opt.direction, opt.rect, icon_rect) icon_rect = self._style.visualRect(opt.direction, opt.rect, icon_rect)
qtutils.qt_ensure_valid(icon_rect) qtutils.ensure_valid(icon_rect)
return icon_rect return icon_rect

View File

@ -301,7 +301,7 @@ class WebView(QWebView):
Emit: Emit:
titleChanged titleChanged
""" """
qtutils.qt_ensure_valid(url) qtutils.ensure_valid(url)
urlstr = url.toDisplayString() urlstr = url.toDisplayString()
log.webview.debug("New title: {}".format(urlstr)) log.webview.debug("New title: {}".format(urlstr))
self.titleChanged.emit(urlstr) self.titleChanged.emit(urlstr)
@ -358,7 +358,7 @@ class WebView(QWebView):
@pyqtSlot('QUrl') @pyqtSlot('QUrl')
def on_url_changed(self, url): def on_url_changed(self, url):
"""Update cur_url when URL has changed.""" """Update cur_url when URL has changed."""
qtutils.qt_ensure_valid(url) qtutils.ensure_valid(url)
self.cur_url = url self.cur_url = url
@pyqtSlot(str, str) @pyqtSlot(str, str)