diff options
author | Friedemann Kleint <Friedemann.Kleint@qt.io> | 2018-06-01 13:23:44 +0200 |
---|---|---|
committer | Friedemann Kleint <Friedemann.Kleint@qt.io> | 2018-06-01 13:23:48 +0200 |
commit | e4e72eae189e57c255193aa8ee556a3d9936d110 (patch) | |
tree | 56c79d8d75479d71d341f5682531fdbd11f6ec95 /examples/webenginewidgets/tabbedbrowser/bookmarkwidget.py | |
parent | 6383820c4b32395fe6dfead79f38ff93b7a0e686 (diff) | |
parent | ae0aa898a3bc1701499ff7993c8d31bc86eb1675 (diff) |
Merge remote-tracking branch 'origin/5.9' into 5.11
Change-Id: I31a0ff26bc02e6cc2ec2a816c16d170fc334f800
Diffstat (limited to 'examples/webenginewidgets/tabbedbrowser/bookmarkwidget.py')
-rw-r--r-- | examples/webenginewidgets/tabbedbrowser/bookmarkwidget.py | 188 |
1 files changed, 94 insertions, 94 deletions
diff --git a/examples/webenginewidgets/tabbedbrowser/bookmarkwidget.py b/examples/webenginewidgets/tabbedbrowser/bookmarkwidget.py index 0224c4518..01a69b921 100644 --- a/examples/webenginewidgets/tabbedbrowser/bookmarkwidget.py +++ b/examples/webenginewidgets/tabbedbrowser/bookmarkwidget.py @@ -47,11 +47,11 @@ from PySide2.QtGui import QIcon, QPixmap, QStandardItem, QStandardItemModel from PySide2.QtWidgets import (QAction, QDockWidget, QMenu, QMessageBox, QToolBar, QTreeView, QWidget) -_urlRole = Qt.UserRole + 1 +_url_role = Qt.UserRole + 1 # Default bookmarks as an array of arrays which is the form # used to read from/write to a .json bookmarks file -_defaultBookMarks = [ +_default_bookmarks = [ ['Tool Bar'], ['http://qt.io', 'Qt', ':/qt-project.org/qmessagebox/images/qtlogo-64.png'], ['https://download.qt.io/snapshots/ci/pyside/', 'Downloads'], @@ -62,60 +62,60 @@ _defaultBookMarks = [ ['Other Bookmarks'] ] -def _configDir(): +def _config_dir(): return '{}/QtForPythonBrowser'.format( QStandardPaths.writableLocation(QStandardPaths.ConfigLocation)) -_bookmarkFile = 'bookmarks.json' +_bookmark_file = 'bookmarks.json' -def _createFolderItem(title): +def _create_folder_item(title): result = QStandardItem(title) result.setFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable) return result -def _createItem(url, title, icon): +def _create_item(url, title, icon): result = QStandardItem(title) result.setFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable) - result.setData(url, _urlRole) + result.setData(url, _url_role) if icon is not None: result.setIcon(icon) return result # Create the model from an array of arrays -def _createModel(parent, serializedBookmarks): +def _create_model(parent, serialized_bookmarks): result = QStandardItemModel(0, 1, parent) - lastFolderItem = None - for entry in serializedBookmarks: + last_folder_item = None + for entry in serialized_bookmarks: if len(entry) == 1: - lastFolderItem = _createFolderItem(entry[0]) - result.appendRow(lastFolderItem) + last_folder_item = _create_folder_item(entry[0]) + result.appendRow(last_folder_item) else: url = QUrl.fromUserInput(entry[0]) title = entry[1] icon = QIcon(entry[2]) if len(entry) > 2 and entry[2] else None - lastFolderItem.appendRow(_createItem(url, title, icon)) + last_folder_item.appendRow(_create_item(url, title, icon)) return result # Serialize model into an array of arrays, writing out the icons # into .png files under directory in the process -def _serializeModel(model, directory): +def _serialize_model(model, directory): result = [] - folderCount = model.rowCount() - for f in range(0, folderCount): - folderItem = model.item(f) - result.append([folderItem.text()]) - itemCount = folderItem.rowCount() - for i in range(0, itemCount): - item = folderItem.child(i) - entry = [item.data(_urlRole).toString(), item.text()] + folder_count = model.rowCount() + for f in range(0, folder_count): + folder_item = model.item(f) + result.append([folder_item.text()]) + item_count = folder_item.rowCount() + for i in range(0, item_count): + item = folder_item.child(i) + entry = [item.data(_url_role).toString(), item.text()] icon = item.icon() if not icon.isNull(): - iconSizes = icon.availableSizes() - largestSize = iconSizes[len(iconSizes) - 1] - iconFileName = '{}/icon{:02}_{:02}_{}.png'.format(directory, - f, i, largestSize.width()) - icon.pixmap(largestSize).save(iconFileName, 'PNG') - entry.append(iconFileName) + icon_sizes = icon.availableSizes() + largest_size = icon_sizes[len(icon_sizes) - 1] + icon_file_name = '{}/icon{:02}_{:02}_{}.png'.format(directory, + f, i, largest_size.width()) + icon.pixmap(largest_size).save(icon_file_name, 'PNG') + entry.append(icon_file_name) result.append(entry) return result @@ -123,8 +123,8 @@ def _serializeModel(model, directory): # functionality to persist and populate tool bars and menus. class BookmarkWidget(QTreeView): - openBookmark = QtCore.Signal(QUrl) - openBookmarkInNewTab = QtCore.Signal(QUrl) + open_bookmark = QtCore.Signal(QUrl) + open_bookmark_in_new_tab = QtCore.Signal(QUrl) changed = QtCore.Signal() def __init__(self): @@ -132,7 +132,7 @@ class BookmarkWidget(QTreeView): self.setRootIsDecorated(False) self.setUniformRowHeights(True) self.setHeaderHidden(True) - self._model = _createModel(self, self._readBookmarks()) + self._model = _create_model(self, self._read_bookmarks()) self.setModel(self._model) self.expandAll() self.activated.connect(self._activated) @@ -147,120 +147,120 @@ class BookmarkWidget(QTreeView): def _activated(self, index): item = self._model.itemFromIndex(index) - self.openBookmark.emit(item.data(_urlRole)) + self.open_bookmark.emit(item.data(_url_role)) - def _actionActivated(self, index): + def _action_activated(self, index): action = self.sender() - self.openBookmark.emit(action.data()) + self.open_bookmark.emit(action.data()) - def _toolBarItem(self): + def _tool_bar_item(self): return self._model.item(0, 0) - def _otherItem(self): + def _other_item(self): return self._model.item(1, 0) - def addBookmark(self, url, title, icon): - self._otherItem().appendRow(_createItem(url, title, icon)) + def add_bookmark(self, url, title, icon): + self._other_item().appendRow(_create_item(url, title, icon)) - def addToolBarBookmark(self, url, title, icon): - self._toolBarItem().appendRow(_createItem(url, title, icon)) + def add_tool_bar_bookmark(self, url, title, icon): + self._tool_bar_item().appendRow(_create_item(url, title, icon)) - # Synchronize the bookmarks under parentItem to a targetObject + # Synchronize the bookmarks under parent_item to a target_object # like QMenu/QToolBar, which has a list of actions. Update # the existing actions, append new ones if needed or hide # superfluous ones - def _populateActions(self, parentItem, targetObject, firstAction): - existingActions = targetObject.actions() - existingActionCount = len(existingActions) - a = firstAction - rowCount = parentItem.rowCount() - for r in range(0, rowCount): - item = parentItem.child(r) + def _populate_actions(self, parent_item, target_object, first_action): + existing_actions = target_object.actions() + existing_action_count = len(existing_actions) + a = first_action + row_count = parent_item.rowCount() + for r in range(0, row_count): + item = parent_item.child(r) title = item.text() icon = item.icon() - url = item.data(_urlRole) - if a < existingActionCount: - action = existingActions[a] + url = item.data(_url_role) + if a < existing_action_count: + action = existing_actions[a] if (title != action.toolTip()): - action.setText(BookmarkWidget.shortTitle(title)) + action.setText(BookmarkWidget.short_title(title)) action.setIcon(icon) action.setToolTip(title) action.setData(url) action.setVisible(True) else: - action = targetObject.addAction(icon, BookmarkWidget.shortTitle(title)) + action = target_object.addAction(icon, BookmarkWidget.short_title(title)) action.setToolTip(title) action.setData(url) - action.triggered.connect(self._actionActivated) + action.triggered.connect(self._action_activated) a = a + 1 - while a < existingActionCount: - existingActions[a].setVisible(False) + while a < existing_action_count: + existing_actions[a].setVisible(False) a = a + 1 - def populateToolBar(self, toolBar): - self._populateActions(self._toolBarItem(), toolBar, 0) + def populate_tool_bar(self, tool_bar): + self._populate_actions(self._tool_bar_item(), tool_bar, 0) - def populateOther(self, menu, firstAction): - self._populateActions(self._otherItem(), menu, firstAction) + def populate_other(self, menu, first_action): + self._populate_actions(self._other_item(), menu, first_action) - def _currentItem(self): + def _current_item(self): index = self.currentIndex() if index.isValid(): item = self._model.itemFromIndex(index) - if item.parent(): # Exclude top level items + if item.parent(): # exclude top level items return item return None - def contextMenuEvent(self, event): - contextMenu = QMenu() - openInNewTabAction = contextMenu.addAction("Open in New Tab") - removeAction = contextMenu.addAction("Remove...") - currentItem = self._currentItem() - openInNewTabAction.setEnabled(currentItem is not None) - removeAction.setEnabled(currentItem is not None) - chosenAction = contextMenu.exec_(event.globalPos()) - if chosenAction == openInNewTabAction: - self.openBookmarkInNewTab.emit(currentItem.data(_urlRole)) - elif chosenAction == removeAction: - self._removeItem(currentItem) + def context_menu_event(self, event): + context_menu = QMenu() + open_in_new_tab_action = context_menu.addAction("Open in New Tab") + remove_action = context_menu.addAction("Remove...") + current_item = self._current_item() + open_in_new_tab_action.setEnabled(current_item is not None) + remove_action.setEnabled(current_item is not None) + chosen_action = context_menu.exec_(event.globalPos()) + if chosen_action == open_in_new_tab_action: + self.open_bookmarkInNewTab.emit(current_item.data(_url_role)) + elif chosen_action == remove_action: + self._remove_item(current_item) - def _removeItem(self, item): + def _remove_item(self, item): button = QMessageBox.question(self, "Remove", "Would you like to remove \"{}\"?".format(item.text()), QMessageBox.Yes | QMessageBox.No) if button == QMessageBox.Yes: item.parent().removeRow(item.row()) - def writeBookmarks(self): + def write_bookmarks(self): if not self._modified: return - dirPath = _configDir() - nativeDirPath = QDir.toNativeSeparators(dirPath) - dir = QFileInfo(dirPath) + dir_path = _config_dir() + native_dir_path = QDir.toNativeSeparators(dir_path) + dir = QFileInfo(dir_path) if not dir.isDir(): - print('Creating {}...'.format(nativeDirPath)) + print('Creating {}...'.format(native_dir_path)) if not QDir(dir.absolutePath()).mkpath(dir.fileName()): - warnings.warn('Cannot create {}.'.format(nativeDirPath), + warnings.warn('Cannot create {}.'.format(native_dir_path), RuntimeWarning) return - serializedModel = _serializeModel(self._model, dirPath) - bookmarkFileName = os.path.join(nativeDirPath, _bookmarkFile) - print('Writing {}...'.format(bookmarkFileName)) - with open(bookmarkFileName, 'w') as bookmarkFile: - json.dump(serializedModel, bookmarkFile, indent = 4) + serialized_model = _serialize_model(self._model, dir_path) + bookmark_file_name = os.path.join(native_dir_path, _bookmark_file) + print('Writing {}...'.format(bookmark_file_name)) + with open(bookmark_file_name, 'w') as bookmark_file: + json.dump(serialized_model, bookmark_file, indent = 4) - def _readBookmarks(self): - bookmarkFileName = os.path.join(QDir.toNativeSeparators(_configDir()), - _bookmarkFile) - if os.path.exists(bookmarkFileName): - print('Reading {}...'.format(bookmarkFileName)) - return json.load(open(bookmarkFileName)) - return _defaultBookMarks + def _read_bookmarks(self): + bookmark_file_name = os.path.join(QDir.toNativeSeparators(_config_dir()), + _bookmark_file) + if os.path.exists(bookmark_file_name): + print('Reading {}...'.format(bookmark_file_name)) + return json.load(open(bookmark_file_name)) + return _default_bookmarks # Return a short title for a bookmark action, # "Qt | Cross Platform.." -> "Qt" @staticmethod - def shortTitle(t): + def short_title(t): i = t.find(' | ') if i == -1: i = t.find(' - ') |