From 90c1c767095e583d0315e87c0592597020858246 Mon Sep 17 00:00:00 2001 From: Cristian Maureira-Fredes Date: Tue, 29 May 2018 17:37:31 +0200 Subject: Pythonize tabbedbrowser example Change the style of the code to follow PEP8 Change-Id: I93eb0df893e8305b4e65ab5318383433b0655625 Reviewed-by: Friedemann Kleint --- .../tabbedbrowser/bookmarkwidget.py | 188 ++++----- .../tabbedbrowser/browsertabwidget.py | 178 ++++---- .../tabbedbrowser/downloadwidget.py | 100 ++--- .../webenginewidgets/tabbedbrowser/findtoolbar.py | 50 +-- examples/webenginewidgets/tabbedbrowser/main.py | 446 ++++++++++----------- .../tabbedbrowser/webengineview.py | 44 +- 6 files changed, 503 insertions(+), 503 deletions(-) (limited to 'examples') 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(' - ') diff --git a/examples/webenginewidgets/tabbedbrowser/browsertabwidget.py b/examples/webenginewidgets/tabbedbrowser/browsertabwidget.py index 29e3d6a22..d9263be08 100644 --- a/examples/webenginewidgets/tabbedbrowser/browsertabwidget.py +++ b/examples/webenginewidgets/tabbedbrowser/browsertabwidget.py @@ -51,41 +51,41 @@ from PySide2.QtWebEngineWidgets import (QWebEngineDownloadItem, class BrowserTabWidget(QTabWidget): - urlChanged = QtCore.Signal(QUrl) - enabledChanged = QtCore.Signal(QWebEnginePage.WebAction, bool) - downloadRequested = QtCore.Signal(QWebEngineDownloadItem) + url_changed = QtCore.Signal(QUrl) + enabled_changed = QtCore.Signal(QWebEnginePage.WebAction, bool) + download_requested = QtCore.Signal(QWebEngineDownloadItem) - def __init__(self, windowFactoryFunction): + def __init__(self, window_factory_function): super(BrowserTabWidget, self).__init__() self.setTabsClosable(True) - self._windowFactoryFunction = windowFactoryFunction + self._window_factory_function = window_factory_function self._webengineviews = [] - self.currentChanged.connect(self._currentChanged) - self.tabCloseRequested.connect(self.handleTabCloseRequest) - self._actionsEnabled = {} - for webAction in WebEngineView.webActions(): - self._actionsEnabled[webAction] = False - - tabBar = self.tabBar() - tabBar.setSelectionBehaviorOnRemove(QTabBar.SelectPreviousTab) - tabBar.setContextMenuPolicy(Qt.CustomContextMenu) - tabBar.customContextMenuRequested.connect(self._handleTabContextMenu) - - def addBrowserTab(self): - factoryFunc = partial(BrowserTabWidget.addBrowserTab, self) - webEngineView = WebEngineView(factoryFunc, self._windowFactoryFunction) + self.currentChanged.connect(self._current_changed) + self.tabCloseRequested.connect(self.handle_tab_close_request) + self._actions_enabled = {} + for web_action in WebEngineView.web_actions(): + self._actions_enabled[web_action] = False + + tab_bar = self.tabBar() + tab_bar.setSelectionBehaviorOnRemove(QTabBar.SelectPreviousTab) + tab_bar.setContextMenuPolicy(Qt.CustomContextMenu) + tab_bar.customContextMenuRequested.connect(self._handle_tab_context_menu) + + def add_browser_tab(self): + factory_func = partial(BrowserTabWidget.add_browser_tab, self) + web_engine_view = WebEngineView(factory_func, self._window_factory_function) index = self.count() - self._webengineviews.append(webEngineView) + self._webengineviews.append(web_engine_view) title = 'Tab {}'.format(index + 1) - self.addTab(webEngineView, title) - page = webEngineView.page() - page.titleChanged.connect(self._titleChanged) - page.iconChanged.connect(self._iconChanged) - page.profile().downloadRequested.connect(self._downloadRequested) - webEngineView.urlChanged.connect(self._urlChanged) - webEngineView.enabledChanged.connect(self._enabledChanged) + self.addTab(web_engine_view, title) + page = web_engine_view.page() + page.titleChanged.connect(self._title_changed) + page.iconChanged.connect(self._icon_changed) + page.profile().downloadRequested.connect(self._download_requested) + web_engine_view.urlChanged.connect(self._url_changed) + web_engine_view.enabled_changed.connect(self._enabled_changed) self.setCurrentIndex(index) - return webEngineView + return web_engine_view def load(self, url): index = self.currentIndex() @@ -101,120 +101,120 @@ class BrowserTabWidget(QTabWidget): index = self.currentIndex() return self._webengineviews[index].url() if index >= 0 else QUrl() - def _urlChanged(self, url): + def _url_changed(self, url): index = self.currentIndex() if index >= 0 and self._webengineviews[index] == self.sender(): - self.urlChanged.emit(url) + self.url_changed.emit(url) - def _titleChanged(self, title): - index = self._indexOfPage(self.sender()) + def _title_changed(self, title): + index = self._index_of_page(self.sender()) if (index >= 0): - self.setTabText(index, BookmarkWidget.shortTitle(title)) + self.setTabText(index, BookmarkWidget.short_title(title)) - def _iconChanged(self, icon): - index = self._indexOfPage(self.sender()) + def _icon_changed(self, icon): + index = self._index_of_page(self.sender()) if (index >= 0): self.setTabIcon(index, icon) - def _enabledChanged(self, webAction, enabled): + def _enabled_changed(self, web_action, enabled): index = self.currentIndex() if index >= 0 and self._webengineviews[index] == self.sender(): - self._checkEmitEnabledChanged(webAction, enabled) + self._check_emit_enabled_changed(web_action, enabled) - def _checkEmitEnabledChanged(self, webAction, enabled): - if enabled != self._actionsEnabled[webAction]: - self._actionsEnabled[webAction] = enabled - self.enabledChanged.emit(webAction, enabled) + def _check_emit_enabled_changed(self, web_action, enabled): + if enabled != self._actions_enabled[web_action]: + self._actions_enabled[web_action] = enabled + self.enabled_changed.emit(web_action, enabled) - def _currentChanged(self, index): - self._updateActions(index) - self.urlChanged.emit(self.url()) + def _current_changed(self, index): + self._update_actions(index) + self.url_changed.emit(self.url()) - def _updateActions(self, index): + def _update_actions(self, index): if index >= 0 and index < len(self._webengineviews): view = self._webengineviews[index] - for webAction in WebEngineView.webActions(): - enabled = view.isWebActionEnabled(webAction) - self._checkEmitEnabledChanged(webAction, enabled) + for web_action in WebEngineView.web_actions(): + enabled = view.is_web_action_enabled(web_action) + self._check_emit_enabled_changed(web_action, enabled) def back(self): - self._triggerAction(QWebEnginePage.Back) + self._trigger_action(QWebEnginePage.Back) def forward(self): - self._triggerAction(QWebEnginePage.Forward) + self._trigger_action(QWebEnginePage.Forward) def reload(self): - self._triggerAction(QWebEnginePage.Reload) + self._trigger_action(QWebEnginePage.Reload) def undo(self): - self._triggerAction(QWebEnginePage.Undo) + self._trigger_action(QWebEnginePage.Undo) def redo(self): - self._triggerAction(QWebEnginePage.Redo) + self._trigger_action(QWebEnginePage.Redo) def cut(self): - self._triggerAction(QWebEnginePage.Cut) + self._trigger_action(QWebEnginePage.Cut) def copy(self): - self._triggerAction(QWebEnginePage.Copy) + self._trigger_action(QWebEnginePage.Copy) def paste(self): - self._triggerAction(QWebEnginePage.Paste) + self._trigger_action(QWebEnginePage.Paste) - def selectAll(self): - self._triggerAction(QWebEnginePage.SelectAll) + def select_all(self): + self._trigger_action(QWebEnginePage.SelectAll) - def zoomFactor(self): + def zoom_factor(self): return self._webengineviews[0].zoomFactor() if self._webengineviews else 1.0 - def setZoomFactor(self, z): + def set_zoom_factor(self, z): for w in self._webengineviews: w.setZoomFactor(z) - def _handleTabContextMenu(self, point): + def _handle_tab_context_menu(self, point): index = self.tabBar().tabAt(point) if index < 0: return - tabCount = len(self._webengineviews) - contextMenu = QMenu() - duplicateTabAction = contextMenu.addAction("Duplicate Tab") - closeOtherTabsAction = contextMenu.addAction("Close Other Tabs") - closeOtherTabsAction.setEnabled(tabCount > 1) - closeTabsToTheRightAction = contextMenu.addAction("Close Tabs to the Right") - closeTabsToTheRightAction.setEnabled(index < tabCount - 1) - closeTabAction = contextMenu.addAction("&Close Tab") - chosenAction = contextMenu.exec_(self.tabBar().mapToGlobal(point)) - if chosenAction == duplicateTabAction: - currentUrl = self.url() - self.addBrowserTab().load(currentUrl) - elif chosenAction == closeOtherTabsAction: - for t in range(tabCount - 1, -1, -1): + tab_count = len(self._webengineviews) + context_menu = QMenu() + duplicate_tab_action = context_menu.addAction("Duplicate Tab") + close_other_tabs_action = context_menu.addAction("Close Other Tabs") + close_other_tabs_action.setEnabled(tab_count > 1) + close_tabs_to_the_right_action = context_menu.addAction("Close Tabs to the Right") + close_tabs_to_the_right_action.setEnabled(index < tab_count - 1) + close_tab_action = context_menu.addAction("&Close Tab") + chosen_action = context_menu.exec_(self.tabBar().mapToGlobal(point)) + if chosen_action == duplicate_tab_action: + current_url = self.url() + self.add_browser_tab().load(current_url) + elif chosen_action == close_other_tabs_action: + for t in range(tab_count - 1, -1, -1): if t != index: - self.handleTabCloseRequest(t) - elif chosenAction == closeTabsToTheRightAction: - for t in range(tabCount - 1, index, -1): - self.handleTabCloseRequest(t) - elif chosenAction == closeTabAction: - self.handleTabCloseRequest(index) - - def handleTabCloseRequest(self, index): + self.handle_tab_close_request(t) + elif chosen_action == close_tabs_to_the_right_action: + for t in range(tab_count - 1, index, -1): + self.handle_tab_close_request(t) + elif chosen_action == close_tab_action: + self.handle_tab_close_request(index) + + def handle_tab_close_request(self, index): if (index >= 0 and self.count() > 1): self._webengineviews.remove(self._webengineviews[index]) self.removeTab(index) - def closeCurrentTab(self): - self.handleTabCloseRequest(self.currentIndex()) + def close_current_tab(self): + self.handle_tab_close_request(self.currentIndex()) - def _triggerAction(self, action): + def _trigger_action(self, action): index = self.currentIndex() if index >= 0: self._webengineviews[index].page().triggerAction(action) - def _indexOfPage(self, webPage): + def _index_of_page(self, web_page): for p in range(0, len(self._webengineviews)): - if (self._webengineviews[p].page() == webPage): + if (self._webengineviews[p].page() == web_page): return p return -1 - def _downloadRequested(self, item): + def _download_requested(self, item): self.downloadRequested.emit(item) diff --git a/examples/webenginewidgets/tabbedbrowser/downloadwidget.py b/examples/webenginewidgets/tabbedbrowser/downloadwidget.py index bcfc7a5ed..030dfc14b 100644 --- a/examples/webenginewidgets/tabbedbrowser/downloadwidget.py +++ b/examples/webenginewidgets/tabbedbrowser/downloadwidget.py @@ -50,95 +50,95 @@ from PySide2.QtWebEngineWidgets import QWebEngineDownloadItem class DownloadWidget(QProgressBar): finished = QtCore.Signal() - removeRequested = QtCore.Signal() + remove_requested = QtCore.Signal() - def __init__(self, downloadItem): + def __init__(self, download_item): super(DownloadWidget, self).__init__() - self._downloadItem = downloadItem - downloadItem.finished.connect(self._finished) - downloadItem.downloadProgress.connect(self._downloadProgress) - downloadItem.stateChanged.connect(self._updateToolTip()) - path = downloadItem.path() + self._download_item = download_item + download_item.finished.connect(self._finished) + download_item.downloadProgress.connect(self._download_progress) + download_item.stateChanged.connect(self._update_tool_tip()) + path = download_item.path() self.setMaximumWidth(300) # Shorten 'PySide2-5.11.0a1-5.11.0-cp36-cp36m-linux_x86_64.whl'... description = QFileInfo(path).fileName() - descriptionLength = len(description) - if descriptionLength > 30: - description = '{}...{}'.format(description[0:10], description[descriptionLength - 10:]) + description_length = len(description) + if description_length > 30: + description = '{}...{}'.format(description[0:10], description[description_length - 10:]) self.setFormat('{} %p%'.format(description)) self.setOrientation(Qt.Horizontal) self.setMinimum(0) self.setValue(0) self.setMaximum(100) - self._updateToolTip() + self._update_tool_tip() # Force progress bar text to be shown on macoS by using 'fusion' style if sys.platform == 'darwin': self.setStyle(QStyleFactory.create('fusion')) @staticmethod - def openFile(file): + def open_file(file): QDesktopServices.openUrl(QUrl.fromLocalFile(file)) @staticmethod - def openDownloadDirectory(): + def open_download_directory(): path = QStandardPaths.writableLocation(QStandardPaths.DownloadLocation) - DownloadWidget.openFile(path) + DownloadWidget.open_file(path) def state(self): - return self._downloadItem.state() + return self._download_item.state() - def _updateToolTip(self): - path = self._downloadItem.path() - toolTip = "{}\n{}".format(self._downloadItem.url().toString(), + def _update_tool_tip(self): + path = self._download_item.path() + tool_tip = "{}\n{}".format(self._download_item.url().toString(), QDir.toNativeSeparators(path)) - totalBytes = self._downloadItem.totalBytes() - if totalBytes > 0: - toolTip += "\n{}K".format(totalBytes / 1024) + total_bytes = self._download_item.total_bytes() + if total_bytes > 0: + tool_tip += "\n{}K".format(total_bytes / 1024) state = self.state() if state == QWebEngineDownloadItem.DownloadRequested: - toolTip += "\n(requested)" + tool_tip += "\n(requested)" elif state == QWebEngineDownloadItem.DownloadInProgress: - toolTip += "\n(downloading)" + tool_tip += "\n(downloading)" elif state == QWebEngineDownloadItem.DownloadCompleted: - toolTip += "\n(completed)" + tool_tip += "\n(completed)" elif state == QWebEngineDownloadItem.DownloadCancelled: - toolTip += "\n(cancelled)" + tool_tip += "\n(cancelled)" else: - toolTip += "\n(interrupted)" - self.setToolTip(toolTip) + tool_tip += "\n(interrupted)" + self.setToolTip(tool_tip) - def _downloadProgress(self, bytesReceived, bytesTotal): - self.setValue(int(100 * bytesReceived / bytesTotal)) + def _download_progress(self, bytes_received, bytes_total): + self.setValue(int(100 * bytes_received / bytes_total)) def _finished(self): - self._updateToolTip() + self._update_tool_tip() self.finished.emit() def _launch(self): - DownloadWidget.openFile(self._downloadItem.path()) + DownloadWidget.open_file(self._download_item.path()) - def mouseDoubleClickEvent(self, event): + def mouse_double_click_event(self, event): if self.state() == QWebEngineDownloadItem.DownloadCompleted: self._launch() - def contextMenuEvent(self, event): + def context_menu_event(self, event): state = self.state() - contextMenu = QMenu() - launchAction = contextMenu.addAction("Launch") - launchAction.setEnabled(state == QWebEngineDownloadItem.DownloadCompleted) - showInFolderAction = contextMenu.addAction("Show in Folder") - showInFolderAction.setEnabled(state == QWebEngineDownloadItem.DownloadCompleted) - cancelAction = contextMenu.addAction("Cancel") - cancelAction.setEnabled(state == QWebEngineDownloadItem.DownloadInProgress) - removeAction = contextMenu.addAction("Remove") - removeAction.setEnabled(state != QWebEngineDownloadItem.DownloadInProgress) + context_menu = QMenu() + launch_action = context_menu.addAction("Launch") + launch_action.setEnabled(state == QWebEngineDownloadItem.DownloadCompleted) + show_in_folder_action = context_menu.addAction("Show in Folder") + show_in_folder_action.setEnabled(state == QWebEngineDownloadItem.DownloadCompleted) + cancel_action = context_menu.addAction("Cancel") + cancel_action.setEnabled(state == QWebEngineDownloadItem.DownloadInProgress) + remove_action = context_menu.addAction("Remove") + remove_action.setEnabled(state != QWebEngineDownloadItem.DownloadInProgress) - chosenAction = contextMenu.exec_(event.globalPos()) - if chosenAction == launchAction: + chosen_action = context_menu.exec_(event.globalPos()) + if chosen_action == launch_action: self._launch() - elif chosenAction == showInFolderAction: - DownloadWidget.openFile(QFileInfo(self._downloadItem.path()).absolutePath()) - elif chosenAction == cancelAction: - self._downloadItem.cancel() - elif chosenAction == removeAction: - self.removeRequested.emit() + elif chosen_action == show_in_folder_action: + DownloadWidget.open_file(QFileInfo(self._download_item.path()).absolutePath()) + elif chosen_action == cancel_action: + self._download_item.cancel() + elif chosen_action == remove_action: + self.remove_requested.emit() diff --git a/examples/webenginewidgets/tabbedbrowser/findtoolbar.py b/examples/webenginewidgets/tabbedbrowser/findtoolbar.py index e862a5cf3..68a1fd595 100644 --- a/examples/webenginewidgets/tabbedbrowser/findtoolbar.py +++ b/examples/webenginewidgets/tabbedbrowser/findtoolbar.py @@ -52,25 +52,25 @@ class FindToolBar(QToolBar): def __init__(self): super(FindToolBar, self).__init__() - self._lineEdit = QLineEdit() - self._lineEdit.setClearButtonEnabled(True) - self._lineEdit.setPlaceholderText("Find...") - self._lineEdit.setMaximumWidth(300) - self._lineEdit.returnPressed.connect(self._findNext) - self.addWidget(self._lineEdit) + self._line_edit = QLineEdit() + self._line_edit.setClearButtonEnabled(True) + self._line_edit.setPlaceholderText("Find...") + self._line_edit.setMaximumWidth(300) + self._line_edit.returnPressed.connect(self._find_next) + self.addWidget(self._line_edit) - self._previousButton = QToolButton() - self._previousButton.setIcon(QIcon(':/qt-project.org/styles/commonstyle/images/up-32.png')) - self._previousButton.clicked.connect(self._findPrevious) - self.addWidget(self._previousButton) + self._previous_button = QToolButton() + self._previous_button.setIcon(QIcon(':/qt-project.org/styles/commonstyle/images/up-32.png')) + self._previous_button.clicked.connect(self._find_previous) + self.addWidget(self._previous_button) - self._nextButton = QToolButton() - self._nextButton.setIcon(QIcon(':/qt-project.org/styles/commonstyle/images/down-32.png')) - self._nextButton.clicked.connect(self._findNext) - self.addWidget(self._nextButton) + self._next_button = QToolButton() + self._next_button.setIcon(QIcon(':/qt-project.org/styles/commonstyle/images/down-32.png')) + self._next_button.clicked.connect(self._find_next) + self.addWidget(self._next_button) - self._caseSensitiveCheckBox = QCheckBox('Case Sensitive') - self.addWidget(self._caseSensitiveCheckBox) + self._case_sensitive_checkbox = QCheckBox('Case Sensitive') + self.addWidget(self._case_sensitive_checkbox) self._hideButton = QToolButton() self._hideButton.setShortcut(QKeySequence(Qt.Key_Escape)) @@ -78,21 +78,21 @@ class FindToolBar(QToolBar): self._hideButton.clicked.connect(self.hide) self.addWidget(self._hideButton) - def focusFind(self): - self._lineEdit.setFocus() + def focus_find(self): + self._line_edit.setFocus() - def _emitFind(self, backward): - needle = self._lineEdit.text().strip() + def _emit_find(self, backward): + needle = self._line_edit.text().strip() if needle: flags = QWebEnginePage.FindFlags() - if self._caseSensitiveCheckBox.isChecked(): + if self._case_sensitive_checkbox.isChecked(): flags |= QWebEnginePage.FindCaseSensitively if backward: flags |= QWebEnginePage.FindBackward self.find.emit(needle, flags) - def _findNext(self): - self._emitFind(False) + def _find_next(self): + self._emit_find(False) - def _findPrevious(self): - self._emitFind(True) + def _find_previous(self): + self._emit_find(True) diff --git a/examples/webenginewidgets/tabbedbrowser/main.py b/examples/webenginewidgets/tabbedbrowser/main.py index 58cc90346..12efdcd5c 100644 --- a/examples/webenginewidgets/tabbedbrowser/main.py +++ b/examples/webenginewidgets/tabbedbrowser/main.py @@ -57,326 +57,326 @@ from PySide2.QtWidgets import (qApp, QAction, QApplication, QDesktopWidget, from PySide2.QtWebEngineWidgets import (QWebEngineDownloadItem, QWebEnginePage, QWebEngineView) -mainWindows = [] +main_windows = [] -def createMainWindow(): - mainWin = MainWindow() - mainWindows.append(mainWin) - availableGeometry = app.desktop().availableGeometry(mainWin) - mainWin.resize(availableGeometry.width() * 2 / 3, availableGeometry.height() * 2 / 3) - mainWin.show() - return mainWin +def create_main_window(): + main_win = MainWindow() + main_windows.append(main_win) + available_geometry = app.desktop().availableGeometry(main_win) + main_win.resize(available_geometry.width() * 2 / 3, available_geometry.height() * 2 / 3) + main_win.show() + return main_win -def createMainWindowWithBrowser(): - mainWin = createMainWindow() - return mainWin.addBrowserTab() +def create_main_window_with_browser(): + main_win = create_main_window() + return main_win.add_browser_tab() class MainWindow(QMainWindow): def __init__(self): super(MainWindow, self).__init__() - self.setWindowTitle('PySide2 Tabbed Browser Example') + self.setWindowTitle('PySide2 tabbed browser Example') - self._tabWidget = BrowserTabWidget(createMainWindowWithBrowser) - self._tabWidget.enabledChanged.connect(self._enabledChanged) - self._tabWidget.downloadRequested.connect(self._downloadRequested) - self.setCentralWidget(self._tabWidget) - self.connect(self._tabWidget, QtCore.SIGNAL("urlChanged(QUrl)"), - self.urlChanged) + self._tab_widget = BrowserTabWidget(create_main_window_with_browser) + self._tab_widget.enabled_changed.connect(self._enabled_changed) + self._tab_widget.download_requested.connect(self._download_requested) + self.setCentralWidget(self._tab_widget) + self.connect(self._tab_widget, QtCore.SIGNAL("url_changed(QUrl)"), + self.url_changed) - self._bookmarkDock = QDockWidget() - self._bookmarkDock.setWindowTitle('Bookmarks') - self._bookmarkWidget = BookmarkWidget() - self._bookmarkWidget.openBookmark.connect(self.loadUrl) - self._bookmarkWidget.openBookmarkInNewTab.connect(self.loadUrlInNewTab) - self._bookmarkDock.setWidget(self._bookmarkWidget) - self.addDockWidget(Qt.LeftDockWidgetArea, self._bookmarkDock) + self._bookmark_dock = QDockWidget() + self._bookmark_dock.setWindowTitle('Bookmarks') + self._bookmark_widget = BookmarkWidget() + self._bookmark_widget.open_bookmark.connect(self.load_url) + self._bookmark_widget.open_bookmark_in_new_tab.connect(self.load_url_in_new_tab) + self._bookmark_dock.setWidget(self._bookmark_widget) + self.addDockWidget(Qt.LeftDockWidgetArea, self._bookmark_dock) - self._findToolBar = None + self._find_tool_bar = None self._actions = {} - self._createMenu() + self._create_menu() - self._toolBar = QToolBar() - self.addToolBar(self._toolBar) + self._tool_bar = QToolBar() + self.addToolBar(self._tool_bar) for action in self._actions.values(): if not action.icon().isNull(): - self._toolBar.addAction(action) + self._tool_bar.addAction(action) - self._addressLineEdit = QLineEdit() - self._addressLineEdit.setClearButtonEnabled(True) - self._addressLineEdit.returnPressed.connect(self.load) - self._toolBar.addWidget(self._addressLineEdit) - self._zoomLabel = QLabel() - self.statusBar().addPermanentWidget(self._zoomLabel) - self._updateZoomLabel() + self._addres_line_edit = QLineEdit() + self._addres_line_edit.setClearButtonEnabled(True) + self._addres_line_edit.returnPressed.connect(self.load) + self._tool_bar.addWidget(self._addres_line_edit) + self._zoom_label = QLabel() + self.statusBar().addPermanentWidget(self._zoom_label) + self._update_zoom_label() self._bookmarksToolBar = QToolBar() self.addToolBar(Qt.TopToolBarArea, self._bookmarksToolBar) self.insertToolBarBreak(self._bookmarksToolBar) - self._bookmarkWidget.changed.connect(self._updateBookmarks) - self._updateBookmarks() + self._bookmark_widget.changed.connect(self._update_bookmarks) + self._update_bookmarks() - def _updateBookmarks(self): - self._bookmarkWidget.populateToolBar(self._bookmarksToolBar) - self._bookmarkWidget.populateOther(self._bookmarkMenu, 3) + def _update_bookmarks(self): + self._bookmark_widget.populate_tool_bar(self._bookmarksToolBar) + self._bookmark_widget.populate_other(self._bookmark_menu, 3) - def _createMenu(self): - fileMenu = self.menuBar().addMenu("&File") - exitAction = QAction(QIcon.fromTheme("application-exit"), "E&xit", + def _create_menu(self): + file_menu = self.menuBar().addMenu("&File") + exit_action = QAction(QIcon.fromTheme("application-exit"), "E&xit", self, shortcut = "Ctrl+Q", triggered=qApp.quit) - fileMenu.addAction(exitAction) + file_menu.addAction(exit_action) - navigationMenu = self.menuBar().addMenu("&Navigation") + navigation_menu = self.menuBar().addMenu("&Navigation") - styleIcons = ':/qt-project.org/styles/commonstyle/images/' - backAction = QAction(QIcon.fromTheme("go-previous", - QIcon(styleIcons + 'left-32.png')), + style_icons = ':/qt-project.org/styles/commonstyle/images/' + back_action = QAction(QIcon.fromTheme("go-previous", + QIcon(style_icons + 'left-32.png')), "Back", self, shortcut = QKeySequence(QKeySequence.Back), - triggered = self._tabWidget.back) - self._actions[QWebEnginePage.Back] = backAction - backAction.setEnabled(False) - navigationMenu.addAction(backAction) - forwardAction = QAction(QIcon.fromTheme("go-next", - QIcon(styleIcons + 'right-32.png')), + triggered = self._tab_widget.back) + self._actions[QWebEnginePage.Back] = back_action + back_action.setEnabled(False) + navigation_menu.addAction(back_action) + forward_action = QAction(QIcon.fromTheme("go-next", + QIcon(style_icons + 'right-32.png')), "Forward", self, shortcut = QKeySequence(QKeySequence.Forward), - triggered = self._tabWidget.forward) - forwardAction.setEnabled(False) - self._actions[QWebEnginePage.Forward] = forwardAction + triggered = self._tab_widget.forward) + forward_action.setEnabled(False) + self._actions[QWebEnginePage.Forward] = forward_action - navigationMenu.addAction(forwardAction) - reloadAction = QAction(QIcon(styleIcons + 'refresh-32.png'), + navigation_menu.addAction(forward_action) + reload_action = QAction(QIcon(style_icons + 'refresh-32.png'), "Reload", self, shortcut = QKeySequence(QKeySequence.Refresh), - triggered = self._tabWidget.reload) - self._actions[QWebEnginePage.Reload] = reloadAction - reloadAction.setEnabled(False) - navigationMenu.addAction(reloadAction) + triggered = self._tab_widget.reload) + self._actions[QWebEnginePage.Reload] = reload_action + reload_action.setEnabled(False) + navigation_menu.addAction(reload_action) - navigationMenu.addSeparator() + navigation_menu.addSeparator() - newTabAction = QAction("New Tab", self, + new_tab_action = QAction("New Tab", self, shortcut = 'Ctrl+T', - triggered = self.addBrowserTab) - navigationMenu.addAction(newTabAction) + triggered = self.add_browser_tab) + navigation_menu.addAction(new_tab_action) - closeTabAction = QAction("Close Current Tab", self, + close_tab_action = QAction("Close Current Tab", self, shortcut = "Ctrl+W", - triggered = self._closeCurrentTab) - navigationMenu.addAction(closeTabAction) + triggered = self._close_current_tab) + navigation_menu.addAction(close_tab_action) - editMenu = self.menuBar().addMenu("&Edit") + edit_menu = self.menuBar().addMenu("&Edit") - findAction = QAction("Find", self, + find_action = QAction("Find", self, shortcut = QKeySequence(QKeySequence.Find), - triggered = self._showFind) - editMenu.addAction(findAction) + triggered = self._show_find) + edit_menu.addAction(find_action) - editMenu.addSeparator() - undoAction = QAction("Undo", self, + edit_menu.addSeparator() + undo_action = QAction("Undo", self, shortcut = QKeySequence(QKeySequence.Undo), - triggered = self._tabWidget.undo) - self._actions[QWebEnginePage.Undo] = undoAction - undoAction.setEnabled(False) - editMenu.addAction(undoAction) + triggered = self._tab_widget.undo) + self._actions[QWebEnginePage.Undo] = undo_action + undo_action.setEnabled(False) + edit_menu.addAction(undo_action) - redoAction = QAction("Redo", self, + redo_action = QAction("Redo", self, shortcut = QKeySequence(QKeySequence.Redo), - triggered = self._tabWidget.redo) - self._actions[QWebEnginePage.Redo] = redoAction - redoAction.setEnabled(False) - editMenu.addAction(redoAction) + triggered = self._tab_widget.redo) + self._actions[QWebEnginePage.Redo] = redo_action + redo_action.setEnabled(False) + edit_menu.addAction(redo_action) - editMenu.addSeparator() + edit_menu.addSeparator() - cutAction = QAction("Cut", self, + cut_action = QAction("Cut", self, shortcut = QKeySequence(QKeySequence.Cut), - triggered = self._tabWidget.cut) - self._actions[QWebEnginePage.Cut] = cutAction - cutAction.setEnabled(False) - editMenu.addAction(cutAction) + triggered = self._tab_widget.cut) + self._actions[QWebEnginePage.Cut] = cut_action + cut_action.setEnabled(False) + edit_menu.addAction(cut_action) - copyAction = QAction("Copy", self, + copy_action = QAction("Copy", self, shortcut = QKeySequence(QKeySequence.Copy), - triggered = self._tabWidget.copy) - self._actions[QWebEnginePage.Copy] = copyAction - copyAction.setEnabled(False) - editMenu.addAction(copyAction) + triggered = self._tab_widget.copy) + self._actions[QWebEnginePage.Copy] = copy_action + copy_action.setEnabled(False) + edit_menu.addAction(copy_action) - pasteAction = QAction("Paste", self, + paste_action = QAction("Paste", self, shortcut = QKeySequence(QKeySequence.Paste), - triggered = self._tabWidget.paste) - self._actions[QWebEnginePage.Paste] = pasteAction - pasteAction.setEnabled(False) - editMenu.addAction(pasteAction) + triggered = self._tab_widget.paste) + self._actions[QWebEnginePage.Paste] = paste_action + paste_action.setEnabled(False) + edit_menu.addAction(paste_action) - editMenu.addSeparator() + edit_menu.addSeparator() - selectAllAction = QAction("Select All", self, + select_all_action = QAction("Select All", self, shortcut = QKeySequence(QKeySequence.SelectAll), - triggered = self._tabWidget.selectAll) - self._actions[QWebEnginePage.SelectAll] = selectAllAction - selectAllAction.setEnabled(False) - editMenu.addAction(selectAllAction) + triggered = self._tab_widget.select_all) + self._actions[QWebEnginePage.SelectAll] = select_all_action + select_all_action.setEnabled(False) + edit_menu.addAction(select_all_action) - self._bookmarkMenu = self.menuBar().addMenu("&Bookmarks") - addBookmarkAction = QAction("&Add Bookmark", self, - triggered = self._addBookmark) - self._bookmarkMenu.addAction(addBookmarkAction) - addToolBarBookmarkAction = QAction("&Add Bookmark to Tool Bar", self, - triggered = self._addToolBarBookmark) - self._bookmarkMenu.addAction(addToolBarBookmarkAction) - self._bookmarkMenu.addSeparator() + self._bookmark_menu = self.menuBar().addMenu("&Bookmarks") + add_bookmark_action = QAction("&Add Bookmark", self, + triggered = self._add_bookmark) + self._bookmark_menu.addAction(add_bookmark_action) + add_tool_bar_bookmark_action = QAction("&Add Bookmark to Tool Bar", self, + triggered = self._add_tool_bar_bookmark) + self._bookmark_menu.addAction(add_tool_bar_bookmark_action) + self._bookmark_menu.addSeparator() - toolsMenu = self.menuBar().addMenu("&Tools") - downloadAction = QAction("Open Downloads", self, - triggered = DownloadWidget.openDownloadDirectory) - toolsMenu.addAction(downloadAction) + tools_menu = self.menuBar().addMenu("&Tools") + download_action = QAction("Open Downloads", self, + triggered = DownloadWidget.open_download_directory) + tools_menu.addAction(download_action) - windowMenu = self.menuBar().addMenu("&Window") + window_menu = self.menuBar().addMenu("&Window") - windowMenu.addAction(self._bookmarkDock.toggleViewAction()) + window_menu.addAction(self._bookmark_dock.toggleViewAction()) - windowMenu.addSeparator() + window_menu.addSeparator() - zoomInAction = QAction(QIcon.fromTheme("zoom-in"), + zoom_in_action = QAction(QIcon.fromTheme("zoom-in"), "Zoom In", self, shortcut = QKeySequence(QKeySequence.ZoomIn), - triggered = self._zoomIn) - windowMenu.addAction(zoomInAction) - zoomOutAction = QAction(QIcon.fromTheme("zoom-out"), + triggered = self._zoom_in) + window_menu.addAction(zoom_in_action) + zoom_out_action = QAction(QIcon.fromTheme("zoom-out"), "Zoom Out", self, shortcut = QKeySequence(QKeySequence.ZoomOut), - triggered = self._zoomOut) - windowMenu.addAction(zoomOutAction) + triggered = self._zoom_out) + window_menu.addAction(zoom_out_action) - resetZoomAction = QAction(QIcon.fromTheme("zoom-original"), + reset_zoom_action = QAction(QIcon.fromTheme("zoom-original"), "Reset Zoom", self, shortcut = "Ctrl+0", - triggered = self._resetZoom) - windowMenu.addAction(resetZoomAction) + triggered = self._reset_zoom) + window_menu.addAction(reset_zoom_action) - aboutMenu = self.menuBar().addMenu("&About") - aboutAction = QAction("About Qt", self, + about_menu = self.menuBar().addMenu("&About") + about_action = QAction("About Qt", self, shortcut = QKeySequence(QKeySequence.HelpContents), triggered=qApp.aboutQt) - aboutMenu.addAction(aboutAction) + about_menu.addAction(about_action) - def addBrowserTab(self): - return self._tabWidget.addBrowserTab() + def add_browser_tab(self): + return self._tab_widget.add_browser_tab() - def _closeCurrentTab(self): - if self._tabWidget.count() > 1: - self._tabWidget.closeCurrentTab() + def _close_current_tab(self): + if self._tab_widget.count() > 1: + self._tab_widget.close_current_tab() else: self.close() - def closeEvent(self, event): - mainWindows.remove(self) + def close_event(self, event): + main_windows.remove(self) event.accept() def load(self): - urlString = self._addressLineEdit.text().strip() - if urlString: - self.loadUrlString(urlString) + url_string = self._addres_line_edit.text().strip() + if url_string: + self.load_url_string(url_string) - def loadUrlString(self, urlS): - url = QUrl.fromUserInput(urlS) + def load_url_string(self, url_s): + url = QUrl.fromUserInput(url_s) if (url.isValid()): - self.loadUrl(url) + self.load_url(url) - def loadUrl(self, url): - self._tabWidget.load(url) + def load_url(self, url): + self._tab_widget.load(url) - def loadUrlInNewTab(self, url): - self.addBrowserTab().load(url) + def load_url_in_new_tab(self, url): + self.add_browser_tab().load(url) - def urlChanged(self, url): - self._addressLineEdit.setText(url.toString()) + def url_changed(self, url): + self._addres_line_edit.setText(url.toString()) - def _enabledChanged(self, webAction, enabled): - action = self._actions[webAction] + def _enabled_changed(self, web_action, enabled): + action = self._actions[web_action] if action: action.setEnabled(enabled) - def _addBookmark(self): - index = self._tabWidget.currentIndex() + def _add_bookmark(self): + index = self._tab_widget.currentIndex() if index >= 0: - url = self._tabWidget.url() - title = self._tabWidget.tabText(index) - icon = self._tabWidget.tabIcon(index) - self._bookmarkWidget.addBookmark(url, title, icon) + url = self._tab_widget.url() + title = self._tab_widget.tabText(index) + icon = self._tab_widget.tabIcon(index) + self._bookmark_widget.add_bookmark(url, title, icon) - def _addToolBarBookmark(self): - index = self._tabWidget.currentIndex() + def _add_tool_bar_bookmark(self): + index = self._tab_widget.currentIndex() if index >= 0: - url = self._tabWidget.url() - title = self._tabWidget.tabText(index) - icon = self._tabWidget.tabIcon(index) - self._bookmarkWidget.addToolBarBookmark(url, title, icon) - - def _zoomIn(self): - newZoom = self._tabWidget.zoomFactor() * 1.5 - if (newZoom <= WebEngineView.maximumZoomFactor()): - self._tabWidget.setZoomFactor(newZoom) - self._updateZoomLabel() - - def _zoomOut(self): - newZoom = self._tabWidget.zoomFactor() / 1.5 - if (newZoom >= WebEngineView.minimumZoomFactor()): - self._tabWidget.setZoomFactor(newZoom) - self._updateZoomLabel() - - def _resetZoom(self): - self._tabWidget.setZoomFactor(1) - self._updateZoomLabel() - - def _updateZoomLabel(self): - percent = int(self._tabWidget.zoomFactor() * 100) - self._zoomLabel.setText("{}%".format(percent)) - - def _downloadRequested(self, item): + url = self._tab_widget.url() + title = self._tab_widget.tabText(index) + icon = self._tab_widget.tabIcon(index) + self._bookmark_widget.add_tool_bar_bookmark(url, title, icon) + + def _zoom_in(self): + new_zoom = self._tab_widget.zoom_factor() * 1.5 + if (new_zoom <= WebEngineView.maximum_zoom_factor()): + self._tab_widget.set_zoom_factor(new_zoom) + self._update_zoom_label() + + def _zoom_out(self): + new_zoom = self._tab_widget.zoom_factor() / 1.5 + if (new_zoom >= WebEngineView.minimum_zoom_factor()): + self._tab_widget.set_zoom_factor(new_zoom) + self._update_zoom_label() + + def _reset_zoom(self): + self._tab_widget.set_zoom_factor(1) + self._update_zoom_label() + + def _update_zoom_label(self): + percent = int(self._tab_widget.zoom_factor() * 100) + self._zoom_label.setText("{}%".format(percent)) + + def _download_requested(self, item): # Remove old downloads before opening a new one - for oldDownload in self.statusBar().children(): - if type(oldDownload).__name__ == 'DownloadWidget' and \ - oldDownload.state() != QWebEngineDownloadItem.DownloadInProgress: - self.statusBar().removeWidget(oldDownload) - del oldDownload + for old_download in self.statusBar().children(): + if type(old_download).__name__ == 'download_widget' and \ + old_download.state() != QWebEngineDownloadItem.DownloadInProgress: + self.statusBar().removeWidget(old_download) + del old_download item.accept() - downloadWidget = DownloadWidget(item) - downloadWidget.removeRequested.connect(self._removeDownloadRequested, + download_widget = download_widget(item) + download_widget.removeRequested.connect(self._remove_download_requested, Qt.QueuedConnection) - self.statusBar().addWidget(downloadWidget) - - def _removeDownloadRequested(self): - downloadWidget = self.sender() - self.statusBar().removeWidget(downloadWidget) - del downloadWidget - - def _showFind(self): - if self._findToolBar is None: - self._findToolBar = FindToolBar() - self._findToolBar.find.connect(self._tabWidget.find) - self.addToolBar(Qt.BottomToolBarArea, self._findToolBar) + self.statusBar().addWidget(download_widget) + + def _remove_download_requested(self): + download_widget = self.sender() + self.statusBar().removeWidget(download_widget) + del download_widget + + def _show_find(self): + if self._find_tool_bar is None: + self._find_tool_bar = FindToolBar() + self._find_tool_bar.find.connect(self._tab_widget.find) + self.addToolBar(Qt.BottomToolBarArea, self._find_tool_bar) else: - self._findToolBar.show() - self._findToolBar.focusFind() + self._find_tool_bar.show() + self._find_tool_bar.focus_find() - def writeBookmarks(self): - self._bookmarkWidget.writeBookmarks() + def write_bookmarks(self): + self._bookmark_widget.write_bookmarks() if __name__ == '__main__': app = QApplication(sys.argv) - mainWin = createMainWindow() - initialUrls = sys.argv[1:] - if not initialUrls: - initialUrls.append('http://qt.io') - for url in initialUrls: - mainWin.loadUrlInNewTab(QUrl.fromUserInput(url)) - exitCode = app.exec_() - mainWin.writeBookmarks() - sys.exit(exitCode) + main_win = create_main_window() + initial_urls = sys.argv[1:] + if not initial_urls: + initial_urls.append('http://qt.io') + for url in initial_urls: + main_win.load_url_in_new_tab(QUrl.fromUserInput(url)) + exit_code = app.exec_() + main_win.write_bookmarks() + sys.exit(exit_code) diff --git a/examples/webenginewidgets/tabbedbrowser/webengineview.py b/examples/webenginewidgets/tabbedbrowser/webengineview.py index 7bef74dfe..7b5775bc8 100644 --- a/examples/webenginewidgets/tabbedbrowser/webengineview.py +++ b/examples/webenginewidgets/tabbedbrowser/webengineview.py @@ -43,7 +43,7 @@ from PySide2.QtWebEngineWidgets import QWebEnginePage, QWebEngineView from PySide2 import QtCore -_webActions = [QWebEnginePage.Back, QWebEnginePage.Forward, +_web_actions = [QWebEnginePage.Back, QWebEnginePage.Forward, QWebEnginePage.Reload, QWebEnginePage.Undo, QWebEnginePage.Redo, QWebEnginePage.Cut, QWebEnginePage.Copy, @@ -51,40 +51,40 @@ _webActions = [QWebEnginePage.Back, QWebEnginePage.Forward, class WebEngineView(QWebEngineView): - enabledChanged = QtCore.Signal(QWebEnginePage.WebAction, bool) + enabled_changed = QtCore.Signal(QWebEnginePage.WebAction, bool) @staticmethod - def webActions(): - return _webActions + def web_actions(): + return _web_actions @staticmethod - def minimumZoomFactor(): + def minimum_zoom_factor(): return 0.25 @staticmethod - def maximumZoomFactor(): + def maximum_zoom_factor(): return 5 - def __init__(self, tabFactoryFunc, windowFactoryFunc): + def __init__(self, tab_factory_func, window_factory_func): super(WebEngineView, self).__init__() - self._tabFactoryFunc = tabFactoryFunc - self._windowFactoryFunc = windowFactoryFunc + self._tab_factory_func = tab_factory_func + self._window_factory_func = window_factory_func page = self.page() self._actions = {} - for webAction in WebEngineView.webActions(): - action = page.action(webAction) - action.changed.connect(self._enabledChanged) - self._actions[action] = webAction + for web_action in WebEngineView.web_actions(): + action = page.action(web_action) + action.changed.connect(self._enabled_changed) + self._actions[action] = web_action - def isWebActionEnabled(self, webAction): - return self.page().action(webAction).isEnabled() + def is_web_action_enabled(self, web_action): + return self.page().action(web_action).isEnabled() - def createWindow(self, windowType): - if windowType == QWebEnginePage.WebBrowserTab or windowType == QWebEnginePage.WebBrowserBackgroundTab: - return self._tabFactoryFunc() - return self._windowFactoryFunc() + def create_window(self, window_type): + if window_type == QWebEnginePage.WebBrowserTab or window_type == QWebEnginePage.WebBrowserBackgroundTab: + return self._tab_factory_func() + return self._window_factory_func() - def _enabledChanged(self): + def _enabled_changed(self): action = self.sender() - webAction = self._actions[action] - self.enabledChanged.emit(webAction, action.isEnabled()) + web_action = self._actions[action] + self.enabled_changed.emit(web_action, action.isEnabled()) -- cgit v1.2.3