本文整理汇总了Python中PyQt5.QtWidgets.QTreeWidget.topLevelItem方法的典型用法代码示例。如果您正苦于以下问题:Python QTreeWidget.topLevelItem方法的具体用法?Python QTreeWidget.topLevelItem怎么用?Python QTreeWidget.topLevelItem使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类PyQt5.QtWidgets.QTreeWidget
的用法示例。
在下文中一共展示了QTreeWidget.topLevelItem方法的9个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: SqlConnectionWidget
# 需要导入模块: from PyQt5.QtWidgets import QTreeWidget [as 别名]
# 或者: from PyQt5.QtWidgets.QTreeWidget import topLevelItem [as 别名]
class SqlConnectionWidget(QWidget):
"""
Class implementing a widget showing the SQL connections.
@signal tableActivated(str) emitted after the entry for a table has been
activated
@signal schemaRequested(str) emitted when the schema display is requested
@signal cleared() emitted after the connection tree has been cleared
"""
tableActivated = pyqtSignal(str)
schemaRequested = pyqtSignal(str)
cleared = pyqtSignal()
def __init__(self, parent=None):
"""
Constructor
@param parent reference to the parent widget (QWidget)
"""
super(SqlConnectionWidget, self).__init__(parent)
layout = QVBoxLayout(self)
layout.setContentsMargins(0, 0, 0, 0)
self.__connectionTree = QTreeWidget(self)
self.__connectionTree.setObjectName("connectionTree")
self.__connectionTree.setHeaderLabels([self.tr("Database")])
if qVersion() >= "5.0.0":
self.__connectionTree.header().setSectionResizeMode(
QHeaderView.Stretch)
else:
self.__connectionTree.header().setResizeMode(QHeaderView.Stretch)
refreshAction = QAction(self.tr("Refresh"), self.__connectionTree)
self.__schemaAction = QAction(
self.tr("Show Schema"), self.__connectionTree)
refreshAction.triggered.connect(self.refresh)
self.__schemaAction.triggered.connect(self.showSchema)
self.__connectionTree.addAction(refreshAction)
self.__connectionTree.addAction(self.__schemaAction)
self.__connectionTree.setContextMenuPolicy(Qt.ActionsContextMenu)
layout.addWidget(self.__connectionTree)
self.__activating = False
self.__connectionTree.itemActivated.connect(self.__itemActivated)
self.__connectionTree.currentItemChanged.connect(
self.__currentItemChanged)
self.__activeDb = ""
def refresh(self):
"""
Public slot to refresh the connection tree.
"""
self.__connectionTree.clear()
self.cleared.emit()
connectionNames = QSqlDatabase.connectionNames()
foundActiveDb = False
for name in connectionNames:
root = QTreeWidgetItem(self.__connectionTree)
db = QSqlDatabase.database(name, False)
root.setText(0, self.__dbCaption(db))
if name == self.__activeDb:
foundActiveDb = True
self.__setActive(root)
if db.isOpen():
tables = db.tables()
for table in tables:
itm = QTreeWidgetItem(root)
itm.setText(0, table)
if not foundActiveDb and connectionNames:
self.__activeDb = connectionNames[0]
self.__setActive(self.__connectionTree.topLevelItem(0))
def showSchema(self):
"""
Public slot to show schema data of a database.
"""
cItm = self.__connectionTree.currentItem()
if cItm is None or cItm.parent() is None:
return
self.__setActive(cItm.parent())
self.schemaRequested.emit(cItm.text(0))
def __itemActivated(self, itm, column):
"""
Private slot handling the activation of an item.
@param itm reference to the item (QTreeWidgetItem)
@param column column that was activated (integer)
"""
if itm is None:
return
#.........这里部分代码省略.........
示例2: ChangedDocumentsListDialog
# 需要导入模块: from PyQt5.QtWidgets import QTreeWidget [as 别名]
# 或者: from PyQt5.QtWidgets.QTreeWidget import topLevelItem [as 别名]
#.........这里部分代码省略.........
if path:
dirname, filename = os.path.split(path)
dirs.setdefault(dirname, []).append((filename, d))
for dirname in sorted(dirs, key=util.naturalsort):
diritem = QTreeWidgetItem()
diritem.setText(0, util.homify(dirname))
self.tree.addTopLevelItem(diritem)
diritem.setExpanded(True)
diritem.setFlags(Qt.ItemIsEnabled)
diritem.setIcon(0, icons.get('folder-open'))
for filename, document in sorted(dirs[dirname],
key=lambda item: util.naturalsort(item[0])):
fileitem = QTreeWidgetItem()
diritem.addChild(fileitem)
if documentwatcher.DocumentWatcher.instance(document).isdeleted():
itemtext = _("[deleted]")
icon = "dialog-error"
else:
itemtext = _("[modified]")
icon = "document-edit"
fileitem.setIcon(0, icons.get(icon))
fileitem.setText(0, filename)
fileitem.setText(1, itemtext)
fileitem.doc = document
# select the item if there is only one
if len(dirs) == 1 and len(list(dirs.values())[0]) == 1:
fileitem.setSelected(True)
self.tree.resizeColumnToContents(0)
self.tree.resizeColumnToContents(1)
self.updateButtons()
def removeDocument(self, document):
"""Remove the specified document from our list."""
for d in range(self.tree.topLevelItemCount()):
diritem = self.tree.topLevelItem(d)
for f in range(diritem.childCount()):
if diritem.child(f).doc is document:
i = diritem.takeChild(f)
i.doc = None
if diritem.childCount() == 0:
self.tree.takeTopLevelItem(d)
break
else:
continue
break
self.updateButtons()
# hide if no documents are left
if self.tree.topLevelItemCount() == 0:
self.hide()
def selectedDocuments(self):
"""Return the selected documents."""
return [i.doc for i in self.tree.selectedItems()]
def allDocuments(self):
"""Return all shown documents."""
return [self.tree.topLevelItem(d).child(f).doc
for d in range(self.tree.topLevelItemCount())
for f in range(self.tree.topLevelItem(d).childCount())]
def updateButtons(self):
"""Updates the buttons regarding the selection."""
docs_sel = self.selectedDocuments()
docs_all = self.allDocuments()
all_deleted_sel = all(documentwatcher.DocumentWatcher.instance(d).isdeleted()
for d in docs_sel)
示例3: MiscTab
# 需要导入模块: from PyQt5.QtWidgets import QTreeWidget [as 别名]
# 或者: from PyQt5.QtWidgets.QTreeWidget import topLevelItem [as 别名]
class MiscTab(QWidget):
def __init__(self, parent=None):
super().__init__(parent)
self.name = self.tr("Misc")
self.markColorLabel = QLabel(self.tr("Default flag colors:"), self)
# TODO: enforce duplicate names avoidance
self.markColorWidget = QTreeWidget(self)
self.markColorWidget.setHeaderLabels(
(self.tr("Color"), self.tr("Name")))
self.markColorWidget.setRootIsDecorated(False)
self.markColorWidget.setSelectionBehavior(
QAbstractItemView.SelectRows)
# TODO: make this work correctly, top-level items only
# self.markColorWidget.setDragDropMode(QAbstractItemView.InternalMove)
self.addItemButton = QPushButton("+", self)
self.addItemButton.clicked.connect(self.addItem)
self.removeItemButton = QPushButton("−", self)
self.removeItemButton.clicked.connect(self.removeItem)
self.loadRecentFileBox = QCheckBox(
self.tr("Load most recent file on start"), self)
layout = QGridLayout(self)
l = 0
layout.addWidget(self.markColorLabel, l, 0, 1, 3)
l += 1
layout.addWidget(self.markColorWidget, l, 0, 1, 3)
l += 1
layout.addWidget(self.addItemButton, l, 0)
layout.addWidget(self.removeItemButton, l, 1)
l += 1
layout.addWidget(self.loadRecentFileBox, l, 0, 1, 3)
self.setLayout(layout)
self.readSettings()
def addItem(self):
def mangleNewName():
name = self.tr("New")
index = 0
while self.markColorWidget.findItems(name, Qt.MatchExactly, 1):
index += 1
name = "{0} ({1})".format(name, index)
return name
# TODO: not DRY with ctor
item = QTreeWidgetItem(self.markColorWidget)
item.setFlags(item.flags() | Qt.ItemIsEditable)
widget = ColorVignette(self)
widget.setColor(QColor(Qt.white))
widget.setMargins(2, 2, 2, 2)
widget.setMayClearColor(False)
self.markColorWidget.setItemWidget(item, 0, widget)
item.setText(1, mangleNewName())
self.markColorWidget.setCurrentItem(item)
self.markColorWidget.editItem(item, 1)
self.removeItemButton.setEnabled(True)
def removeItem(self):
i = self.markColorWidget.selectionModel().currentIndex().row()
self.markColorWidget.takeTopLevelItem(i)
if not self.markColorWidget.topLevelItemCount():
self.removeItemButton.setEnabled(False)
def readSettings(self):
entries = settings.readMarkColors()
for name, color in entries.items():
item = QTreeWidgetItem(self.markColorWidget)
item.setFlags(item.flags() | Qt.ItemIsEditable)
widget = ColorVignette(self)
widget.setColor(color)
widget.setMargins(2, 2, 2, 2)
widget.setMayClearColor(False)
self.markColorWidget.setItemWidget(item, 0, widget)
item.setText(1, name)
if not len(entries):
self.removeItemButton.setEnabled(False)
loadRecentFile = settings.loadRecentFile()
self.loadRecentFileBox.setChecked(loadRecentFile)
def writeSettings(self):
markColors = OrderedDict()
for i in range(self.markColorWidget.topLevelItemCount()):
item = self.markColorWidget.topLevelItem(i)
name = item.text(1)
color = self.markColorWidget.itemWidget(item, 0).color()
markColors[name] = color
settings.writeMarkColors(markColors)
loadRecentFile = self.loadRecentFileBox.isChecked()
settings.setLoadRecentFile(loadRecentFile)
示例4: PugdebugExpressionViewer
# 需要导入模块: from PyQt5.QtWidgets import QTreeWidget [as 别名]
# 或者: from PyQt5.QtWidgets.QTreeWidget import topLevelItem [as 别名]
class PugdebugExpressionViewer(QWidget):
expression_added_signal = pyqtSignal(int, str)
expression_changed_signal = pyqtSignal(int, str)
def __init__(self):
super(PugdebugExpressionViewer, self).__init__()
# Action for adding a new expression
self.add_action = QAction(QIcon.fromTheme('list-add'), "&Add", self)
self.add_action.triggered.connect(self.handle_add_action)
# Action for deleting selected expressions
self.delete_action = QAction(
QIcon.fromTheme('list-remove'),
"&Delete", self
)
self.delete_action.setShortcut(QKeySequence("Del"))
self.delete_action.triggered.connect(self.handle_delete_action)
self.toolbar = QToolBar()
self.toolbar.setIconSize(QSize(16, 16))
self.toolbar.addAction(self.add_action)
self.toolbar.addAction(self.delete_action)
self.tree = QTreeWidget()
self.tree.setColumnCount(3)
self.tree.setHeaderLabels(['Expression', 'Type', 'Value'])
self.tree.setSelectionMode(QAbstractItemView.ContiguousSelection)
self.tree.setContextMenuPolicy(Qt.CustomContextMenu)
self.tree.customContextMenuRequested.connect(self.show_context_menu)
layout = QVBoxLayout()
layout.addWidget(self.toolbar)
layout.addWidget(self.tree)
self.setLayout(layout)
self.restore_state()
self.tree.itemChanged.connect(self.handle_item_changed)
def show_context_menu(self, point):
# Create the context menu on the tree widget
context_menu = QMenu(self)
# Add action is always visible
context_menu.addAction(self.add_action)
# If clicked on an row, offer to delete it
if self.tree.itemAt(point):
context_menu.addAction(self.delete_action)
point = self.tree.mapToGlobal(point)
context_menu.popup(point)
def add_expression(self, expression):
item = QTreeWidgetItem([expression, '', ''])
item.setFlags(
Qt.ItemIsEnabled |
Qt.ItemIsEditable |
Qt.ItemIsSelectable
)
self.tree.addTopLevelItem(item)
# Emit the signal to evaluate the expression
index = self.tree.indexOfTopLevelItem(item)
self.expression_added_signal.emit(index, expression)
def delete_selected(self):
"""Deletes currently selected items from the tree"""
for item in self.tree.selectedItems():
index = self.tree.indexOfTopLevelItem(item)
self.delete_expression(item)
self.select_next(index)
def select_next(self, index):
"""Selects the next item after an item has been deleted"""
prev_item = self.tree.topLevelItem(index - 1)
next_item = self.tree.topLevelItem(index)
if prev_item:
prev_item.setSelected(True)
elif next_item:
next_item.setSelected(True)
def clear_values(self):
"""Deletes values for all expressions"""
count = self.tree.topLevelItemCount()
for index in range(0, count):
item = self.tree.topLevelItem(index)
item.setData(1, Qt.DisplayRole, '')
item.setData(2, Qt.DisplayRole, '')
item.takeChildren()
def delete_expression(self, item):
"""Deletes the given item from the tree"""
index = self.tree.indexOfTopLevelItem(item)
self.tree.takeTopLevelItem(index)
def get_expressions(self):
#.........这里部分代码省略.........
示例5: SessionsManager
# 需要导入模块: from PyQt5.QtWidgets import QTreeWidget [as 别名]
# 或者: from PyQt5.QtWidgets.QTreeWidget import topLevelItem [as 别名]
class SessionsManager(QDialog):
"""Session Manager, to load different configurations of ninja."""
def __init__(self, parent=None):
super(SessionsManager, self).__init__(parent, Qt.Dialog)
self._ninja = parent
self.setModal(True)
self.setWindowTitle(translations.TR_SESSIONS_TITLE)
self.setMinimumWidth(550)
self.setMinimumHeight(450)
self._manager = _SessionManager(parent)
self._load_ui()
def install(self):
self._manager.load_sessions()
def _load_ui(self):
main_layout = QVBoxLayout(self)
main_layout.addWidget(QLabel(translations.TR_SESSIONS_DIALOG_BODY))
main_hbox = QHBoxLayout()
# Session list
session_layout = QVBoxLayout()
self._session_list = QTreeWidget()
self._session_list.setHeaderLabels(["Session", "Last Modified"])
session_layout.addWidget(self._session_list)
# Content frame
content_frame = QFrame()
content_frame.hide()
frame_layout = QVBoxLayout(content_frame)
content_frame.setFrameStyle(QFrame.StyledPanel | QFrame.Sunken)
session_layout.addWidget(content_frame)
frame_layout.setContentsMargins(0, 0, 0, 0)
self._content_list = QTreeWidget()
self._content_list.setHeaderHidden(True)
frame_layout.addWidget(self._content_list)
# Separator line
line_frame = QFrame()
line_frame.setFrameStyle(QFrame.VLine | QFrame.Sunken)
# Buttons
btn_layout = QVBoxLayout()
btn_create = QPushButton(translations.TR_SESSIONS_BTN_CREATE)
btn_activate = QPushButton(translations.TR_SESSIONS_BTN_ACTIVATE)
btn_update = QPushButton(translations.TR_SESSIONS_BTN_UPDATE)
btn_delete = QPushButton(translations.TR_SESSIONS_BTN_DELETE)
btn_details = QPushButton(translations.TR_SESSIONS_BTN_DETAILS)
btn_details.setCheckable(True)
# Add buttons to layout
btn_layout.addWidget(btn_create)
btn_layout.addWidget(btn_activate)
btn_layout.addWidget(btn_update)
btn_layout.addWidget(btn_delete)
btn_layout.addStretch()
btn_layout.addWidget(btn_details)
# Add widgets and layouts to the main layout
main_layout.addLayout(main_hbox)
main_hbox.addLayout(session_layout)
main_hbox.addWidget(line_frame)
main_hbox.addLayout(btn_layout)
main_hbox.setSizeConstraint(QLayout.SetFixedSize)
btn_details.toggled[bool].connect(content_frame.setVisible)
# Connections
self._session_list.itemSelectionChanged.connect(
self.load_session_content)
btn_activate.clicked.connect(self.open_session)
btn_update.clicked.connect(self.save_session)
btn_create.clicked.connect(self.create_session)
btn_delete.clicked.connect(self.delete_session)
def __load_sessions(self):
for session_name in self._manager.sessions:
item = QTreeWidgetItem()
item.setText(0, session_name)
item.setText(1, "FIXME: manage this!")
self._session_list.addTopLevelItem(item)
self._session_list.setCurrentItem(
self._session_list.topLevelItem(0))
def load_session_content(self):
"""Load the selected session, replacing the current session."""
item = self._session_list.currentItem()
self._content_list.clear()
if item is not None:
key = item.text(0)
files, projects = self._manager.get_session(key)
files_parent = QTreeWidgetItem(
self._content_list, [translations.TR_FILES])
for ffile in files:
QTreeWidgetItem(files_parent, [ffile[0]])
projects_parent = QTreeWidgetItem(
self._content_list, [translations.TR_PROJECT])
for project in projects:
QTreeWidgetItem(projects_parent, [project])
files_parent.setExpanded(True)
projects_parent.setExpanded(True)
def create_session(self):
"""Create a new Session."""
session_info = QInputDialog.getText(
None, translations.TR_SESSIONS_CREATE_TITLE,
#.........这里部分代码省略.........
示例6: ImperiumWidget
# 需要导入模块: from PyQt5.QtWidgets import QTreeWidget [as 别名]
# 或者: from PyQt5.QtWidgets.QTreeWidget import topLevelItem [as 别名]
#.........这里部分代码省略.........
#
item_strings = [self.tr('Destroyer')]
total_res = 0
for pl in planets:
total_res += pl.ships.unik
item_strings.append(number_format(pl.ships.unik))
item_strings.append(number_format(total_res))
additem_helper(item_strings, fleet_root)
#
item_strings = [self.tr('Death Star')]
total_res = 0
for pl in planets:
total_res += pl.ships.zs
item_strings.append(number_format(pl.ships.zs))
item_strings.append(number_format(total_res))
additem_helper(item_strings, fleet_root)
#
item_strings = [self.tr('BattleCruiser')]
total_res = 0
for pl in planets:
total_res += pl.ships.lk
item_strings.append(number_format(pl.ships.lk))
item_strings.append(number_format(total_res))
additem_helper(item_strings, fleet_root)
#
item_strings = [self.tr('War Base')]
total_res = 0
for pl in planets:
total_res += pl.ships.warbase
item_strings.append(number_format(pl.ships.warbase))
item_strings.append(number_format(total_res))
additem_helper(item_strings, fleet_root)
#
item_strings = [self.tr('Corvett')]
total_res = 0
for pl in planets:
total_res += pl.ships.f_corvett
item_strings.append(number_format(pl.ships.f_corvett))
item_strings.append(number_format(total_res))
additem_helper(item_strings, fleet_root)
#
item_strings = [self.tr('Interceptor')]
total_res = 0
for pl in planets:
total_res += pl.ships.f_ceptor
item_strings.append(number_format(pl.ships.f_ceptor))
item_strings.append(number_format(total_res))
additem_helper(item_strings, fleet_root)
#
item_strings = [self.tr('Dreadnought')]
total_res = 0
for pl in planets:
total_res += pl.ships.f_dread
item_strings.append(number_format(pl.ships.f_dread))
item_strings.append(number_format(total_res))
additem_helper(item_strings, fleet_root)
#
item_strings = [self.tr('Corsair')]
total_res = 0
for pl in planets:
total_res += pl.ships.f_corsair
item_strings.append(number_format(pl.ships.f_corsair))
item_strings.append(number_format(total_res))
additem_helper(item_strings, fleet_root)
# add/expand
self._tree.addTopLevelItem(fleet_root)
fleet_root.setExpanded(True)
def update_planet_resources(self):
res_top_twi = self._tree.topLevelItem(3) # 4th top level item is "Resources"
if res_top_twi is None:
return
res_met_twi = res_top_twi.child(0) # first child is metal
res_cry_twi = res_top_twi.child(1) # 2nd is crystal
res_deit_twi = res_top_twi.child(2) # 3rd is deit
res_en_twi = res_top_twi.child(3) # 4th is energy
if (res_met_twi is None) or (res_cry_twi is None) or (res_deit_twi is None) \
or (res_en_twi is None):
return
planets = self._world.get_planets() # get planets from the world
ncolumn = 1 # column #0 is description, planets start at #1
totals = [0, 0, 0] # count total resources
for planet in planets:
res_met_twi.setText(ncolumn, number_format(int(planet.res_current.met)))
res_cry_twi.setText(ncolumn, number_format(int(planet.res_current.cry)))
res_deit_twi.setText(ncolumn, number_format(int(planet.res_current.deit)))
res_en_twi.setText(ncolumn, '{0} / {1}'.format(
planet.energy.energy_left, planet.energy.energy_total))
ncolumn += 1
totals[0] += int(planet.res_current.met)
totals[1] += int(planet.res_current.cry)
totals[2] += int(planet.res_current.deit)
# set values for "totals" column
res_met_twi.setText(ncolumn, number_format(totals[0]))
res_cry_twi.setText(ncolumn, number_format(totals[1]))
res_deit_twi.setText(ncolumn, number_format(totals[2]))
@pyqtSlot()
def on_btn_refresh_imperium(self):
self._world.signal(self._world.SIGNAL_RELOAD_PAGE, page_name='imperium')
示例7: EditorConfiguration
# 需要导入模块: from PyQt5.QtWidgets import QTreeWidget [as 别名]
# 或者: from PyQt5.QtWidgets.QTreeWidget import topLevelItem [as 别名]
#.........这里部分代码省略.........
self._checkStyle.setChecked(True)
def _enable_errors_inline(self, val):
"""Method that takes a value to enable the inline errors checking"""
if val == Qt.Checked:
self._checkErrors.setChecked(True)
def _disable_check_style(self, val):
"""Method that takes a value to disable the inline style checking"""
if val == Qt.Unchecked:
self._checkStyleOnLine.setChecked(False)
def _disable_show_errors(self, val):
"""Method that takes a value to disable the inline errors checking"""
if val == Qt.Unchecked:
self._showErrorsOnLine.setChecked(False)
def save(self):
"""Method to save settings"""
qsettings = IDE.ninja_settings()
settings.USE_TABS = bool(self._checkUseTabs.currentIndex())
qsettings.setValue('preferences/editor/useTabs',
settings.USE_TABS)
margin_line = self._spinMargin.value()
settings.MARGIN_LINE = margin_line
settings.pycodestylemod_update_margin_line_length(margin_line)
qsettings.setValue('preferences/editor/marginLine', margin_line)
settings.SHOW_MARGIN_LINE = self._checkShowMargin.isChecked()
qsettings.setValue('preferences/editor/showMarginLine',
settings.SHOW_MARGIN_LINE)
settings.INDENT = self._spin.value()
qsettings.setValue('preferences/editor/indent', settings.INDENT)
endOfLine = self._checkEndOfLine.isChecked()
settings.USE_PLATFORM_END_OF_LINE = endOfLine
qsettings.setValue('preferences/editor/platformEndOfLine', endOfLine)
settings.UNDERLINE_NOT_BACKGROUND = \
bool(self._checkHighlightLine.currentIndex())
qsettings.setValue('preferences/editor/errorsUnderlineBackground',
settings.UNDERLINE_NOT_BACKGROUND)
settings.FIND_ERRORS = self._checkErrors.isChecked()
qsettings.setValue('preferences/editor/errors', settings.FIND_ERRORS)
settings.ERRORS_HIGHLIGHT_LINE = self._showErrorsOnLine.isChecked()
qsettings.setValue('preferences/editor/errorsInLine',
settings.ERRORS_HIGHLIGHT_LINE)
settings.CHECK_STYLE = self._checkStyle.isChecked()
qsettings.setValue('preferences/editor/checkStyle',
settings.CHECK_STYLE)
settings.SHOW_MIGRATION_TIPS = self._showMigrationTips.isChecked()
qsettings.setValue('preferences/editor/showMigrationTips',
settings.SHOW_MIGRATION_TIPS)
settings.CHECK_HIGHLIGHT_LINE = self._checkStyleOnLine.isChecked()
qsettings.setValue('preferences/editor/checkStyleInline',
settings.CHECK_HIGHLIGHT_LINE)
settings.END_AT_LAST_LINE = self._checkEndAtLastLine.isChecked()
qsettings.setValue('preferences/editor/endAtLastLine',
settings.END_AT_LAST_LINE)
settings.REMOVE_TRAILING_SPACES = self._checkTrailing.isChecked()
qsettings.setValue('preferences/editor/removeTrailingSpaces',
settings.REMOVE_TRAILING_SPACES)
settings.ALLOW_WORD_WRAP = self._allowWordWrap.isChecked()
qsettings.setValue('preferences/editor/allowWordWrap',
settings.ALLOW_WORD_WRAP)
settings.SHOW_TABS_AND_SPACES = self._checkShowSpaces.isChecked()
qsettings.setValue('preferences/editor/showTabsAndSpaces',
settings.SHOW_TABS_AND_SPACES)
settings.SHOW_INDENTATION_GUIDE = (
self._checkIndentationGuide.isChecked())
qsettings.setValue('preferences/editor/showIndentationGuide',
settings.SHOW_INDENTATION_GUIDE)
settings.CHECK_FOR_DOCSTRINGS = self._checkForDocstrings.isChecked()
qsettings.setValue('preferences/editor/checkForDocstrings',
settings.CHECK_FOR_DOCSTRINGS)
settings.SHOW_LINE_NUMBERS = self._checkDisplayLineNumbers.isChecked()
qsettings.setValue('preferences/editor/showLineNumbers',
settings.SHOW_LINE_NUMBERS)
current_ignores = set(settings.IGNORE_PEP8_LIST)
new_ignore_codes = []
# Get pep8 from tree widget
for index in range(self._listIgnoreViolations.topLevelItemCount()):
ignore_code = self._listIgnoreViolations.topLevelItem(
index).text(0)
if ignore_code:
new_ignore_codes.append(ignore_code.strip())
# pep8 list that will be removed
to_remove = [x for x in current_ignores
if x not in new_ignore_codes]
# Update list
settings.IGNORE_PEP8_LIST = new_ignore_codes
qsettings.setValue('preferences/editor/defaultIgnorePep8',
settings.IGNORE_PEP8_LIST)
# Add
for ignore_code in settings.IGNORE_PEP8_LIST:
settings.pycodestylemod_add_ignore(ignore_code)
# Remove
for ignore_code in to_remove:
settings.pycodestylemod_remove_ignore(ignore_code)
if settings.USE_TABS:
settings.pycodestylemod_add_ignore("W191")
else:
settings.pycodestylemod_remove_ignore("W191")
示例8: Preferences
# 需要导入模块: from PyQt5.QtWidgets import QTreeWidget [as 别名]
# 或者: from PyQt5.QtWidgets.QTreeWidget import topLevelItem [as 别名]
class Preferences(QDialog):
#
configuration = {}
weight = 0
#
savePreferences = pyqtSignal()
#
def __init__(self, parent=None):
super(Preferences, self).__init__(parent, Qt.Dialog)
self.setWindowTitle(translations.TR_PREFERENCES_TITLE)
self.setMinimumSize(QSize(900, 600))
vbox = QVBoxLayout(self)
hbox = QHBoxLayout()
vbox.setContentsMargins(0, 0, 5, 5)
hbox.setContentsMargins(0, 0, 0, 0)
#
self.tree = QTreeWidget()
self.tree.header().setHidden(True)
self.tree.setSelectionMode(QTreeWidget.SingleSelection)
self.tree.setAnimated(True)
self.tree.header().setHorizontalScrollMode(
QAbstractItemView.ScrollPerPixel)
self.tree.header().setSectionResizeMode(0, QHeaderView.ResizeToContents)
self.tree.header().setStretchLastSection(False)
self.tree.setFixedWidth(200)
self.stacked = QStackedLayout()
hbox.addWidget(self.tree)
hbox.addLayout(self.stacked)
vbox.addLayout(hbox)
#
hbox_footer = QHBoxLayout()
self._btnSave = QPushButton(translations.TR_SAVE)
self._btnCancel = QPushButton(translations.TR_CANCEL)
hbox_footer.addSpacerItem(QSpacerItem(1, 0, QSizePolicy.Expanding))
hbox_footer.addWidget(self._btnCancel)
hbox_footer.addWidget(self._btnSave)
vbox.addLayout(hbox_footer)
#
self.tree.itemSelectionChanged.connect(self._change_current)
self._btnCancel.clicked['bool'].connect(self.close)
self._btnSave.clicked['bool'].connect(self._save_preferences)
#
self.load_ui()
self.tree.setCurrentItem(self.tree.topLevelItem(0))
#
def _save_preferences(self):
self.savePreferences.emit()
self.close()
#
def load_ui(self):
sections = sorted(
list(Preferences.configuration.keys()),
key=lambda item: Preferences.configuration[item]['weight'])
for section in sections:
text = Preferences.configuration[section]['text']
Widget = Preferences.configuration[section]['widget']
widget = Widget(self)
area = QScrollArea()
area.setWidgetResizable(True)
area.setWidget(widget)
self.stacked.addWidget(area)
index = self.stacked.indexOf(area)
item = QTreeWidgetItem([text])
item.setData(0, Qt.UserRole, index)
self.tree.addTopLevelItem(item)
#
#Sort Item Children
subcontent = Preferences.configuration[section].get(
'subsections', {})
subsections = sorted(list(subcontent.keys()),
key=lambda item: subcontent[item]['weight'])
for sub in subsections:
text = subcontent[sub]['text']
Widget = subcontent[sub]['widget']
widget = Widget(self)
area = QScrollArea()
area.setWidgetResizable(True)
area.setWidget(widget)
self.stacked.addWidget(area)
index = self.stacked.indexOf(area)
subitem = QTreeWidgetItem([text])
subitem.setData(0, Qt.UserRole, index)
item.addChild(subitem)
#
self.tree.expandAll()
#
def _change_current(self):
item = self.tree.currentItem()
index = item.data(0, Qt.UserRole)
self.stacked.setCurrentIndex(index)
#
@classmethod
def register_configuration(cls, section, widget, text, weight=None,
subsection=None):
if weight is None:
Preferences.weight += 1
weight = Preferences.weight
if not subsection:
Preferences.configuration[section] = {'widget': widget,
'weight': weight,
#.........这里部分代码省略.........
示例9: Shortcuts
# 需要导入模块: from PyQt5.QtWidgets import QTreeWidget [as 别名]
# 或者: from PyQt5.QtWidgets.QTreeWidget import topLevelItem [as 别名]
class Shortcuts(preferences.Page):
def __init__(self, dialog):
super(Shortcuts, self).__init__(dialog)
layout = QVBoxLayout()
layout.setContentsMargins(0, 0, 0, 0)
self.setLayout(layout)
self.scheme = SchemeSelector(self)
layout.addWidget(self.scheme)
self.searchEntry = LineEdit()
self.searchEntry.setPlaceholderText(_("Search..."))
layout.addWidget(self.searchEntry)
self.tree = QTreeWidget(self)
self.tree.setHeaderLabels([_("Command"), _("Shortcut")])
self.tree.setRootIsDecorated(False)
self.tree.setColumnCount(2)
self.tree.setAllColumnsShowFocus(True)
self.tree.setAnimated(True)
layout.addWidget(self.tree)
self.edit = QPushButton(icons.get("preferences-desktop-keyboard-shortcuts"), '')
layout.addWidget(self.edit)
# signals
self.searchEntry.textChanged.connect(self.updateFilter)
self.scheme.currentChanged.connect(self.slotSchemeChanged)
self.scheme.changed.connect(self.changed)
self.tree.currentItemChanged.connect(self.slotCurrentItemChanged)
self.tree.itemDoubleClicked.connect(self.editCurrentItem)
self.edit.clicked.connect(self.editCurrentItem)
# make a dict of all actions with the actions as key and the names as
# value, with the collection prepended (for loading/saving)
win = dialog.parent()
allactions = {}
for collection in actioncollectionmanager.manager(win).actionCollections():
for name, action in collection.actions().items():
allactions[action] = (collection, name)
# keep a list of actions not in the menu structure
left = list(allactions.keys())
def add_actions(menuitem, actions):
"""Add actions to a QTreeWidgetItem."""
for a in actions:
if a.menu():
item = build_menu_item(a)
if item.childCount():
menuitem.addChild(item)
elif a in left:
left.remove(a)
menuitem.addChild(ShortcutItem(a, *allactions[a]))
menuitem.setFlags(Qt.ItemIsEnabled) # disable selection
def build_menu_item(action):
"""Return a QTreeWidgetItem with children for all the actions in the submenu."""
menuitem = QTreeWidgetItem()
text = qutil.removeAccelerator(action.text())
menuitem.setText(0, _("Menu {name}").format(name=text))
add_actions(menuitem, action.menu().actions())
return menuitem
# present the actions nicely ordered as in the menus
for a in win.menuBar().actions():
menuitem = build_menu_item(a)
if menuitem.childCount():
self.tree.addTopLevelItem(menuitem)
# sort leftover actions
left.sort(key=lambda i: i.text())
# show actions that are left, grouped by collection
titlegroups = {}
for a in left[:]: # copy
collection, name = allactions[a]
if collection.title():
titlegroups.setdefault(collection.title(), []).append(a)
left.remove(a)
for title in sorted(titlegroups):
item = QTreeWidgetItem(["{0}:".format(title)])
for a in titlegroups[title]:
item.addChild(ShortcutItem(a, *allactions[a]))
self.tree.addTopLevelItem(item)
item.setFlags(Qt.ItemIsEnabled) # disable selection
# show other actions that were not in the menus
item = QTreeWidgetItem([_("Other commands:")])
for a in left:
if a.text() and not a.menu():
item.addChild(ShortcutItem(a, *allactions[a]))
if item.childCount():
self.tree.addTopLevelItem(item)
item.setFlags(Qt.ItemIsEnabled) # disable selection
self.tree.expandAll()
item = self.tree.topLevelItem(0).child(0)
if _lastaction:
# find the previously selected item
#.........这里部分代码省略.........