本文整理汇总了Python中PyQt5.QtWidgets.QTreeWidget.currentItem方法的典型用法代码示例。如果您正苦于以下问题:Python QTreeWidget.currentItem方法的具体用法?Python QTreeWidget.currentItem怎么用?Python QTreeWidget.currentItem使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类PyQt5.QtWidgets.QTreeWidget
的用法示例。
在下文中一共展示了QTreeWidget.currentItem方法的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: DiscoveryDialog
# 需要导入模块: from PyQt5.QtWidgets import QTreeWidget [as 别名]
# 或者: from PyQt5.QtWidgets.QTreeWidget import currentItem [as 别名]
class DiscoveryDialog(QDialog):
def __init__(self, parent=None):
super(DiscoveryDialog, self).__init__(parent)
self.setModal(True)
self.setMinimumSize(200,200) # To prevent Geometry error
self.hosts = []
layout = QVBoxLayout()
self.setLayout(layout)
self.serverview = QTreeWidget()
self.serverview.setHeaderLabels(['Server', 'Ports'])
self.serverview.setIndentation(0)
self.serverview.setStyleSheet('padding:0px')
self.serverview.header().resizeSection(0, 180)
layout.addWidget(self.serverview)
btns = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
layout.addWidget(btns)
btns.accepted.connect(self.on_accept)
btns.rejected.connect(parent.closeEvent)
bs.net.server_discovered.connect(self.add_srv)
def add_srv(self, address, ports):
for host in self.hosts:
if address == host.address and ports == host.ports:
# We already know this server, skip
return
host = QTreeWidgetItem(self.serverview)
host.address = address
host.ports = ports
host.hostname = 'This computer' if address == get_ownip() else address
host.setText(0, host.hostname)
host.setText(1, '{},{}'.format(*ports))
self.hosts.append(host)
def on_accept(self):
host = self.serverview.currentItem()
if host:
bs.net.stop_discovery()
hostname = host.address
eport, sport = host.ports
bs.net.connect(hostname=hostname, event_port=eport, stream_port=sport)
self.close()
示例2: ConfigurationWidget
# 需要导入模块: from PyQt5.QtWidgets import QTreeWidget [as 别名]
# 或者: from PyQt5.QtWidgets.QTreeWidget import currentItem [as 别名]
#.........这里部分代码省略.........
"""
Public method to get a reference to the named page.
@param pageName name of the configuration page (string)
@return reference to the page or None, indicating page was
not loaded yet
"""
return self.configItems[pageName][-1]
def getLexers(self):
"""
Public method to get a reference to the lexers dictionary.
@return reference to the lexers dictionary
"""
return self.lexers
def setPreferences(self):
"""
Public method called to store the selected values into the preferences
storage.
"""
for key, pageData in list(self.configItems.items()):
if pageData[-1]:
pageData[-1].save()
# page was loaded (and possibly modified)
QApplication.processEvents() # ensure HMI is responsive
def on_buttonBox_clicked(self, button):
"""
Private slot called by a button of the button box clicked.
@param button button that was clicked (QAbstractButton)
"""
if button == self.buttonBox.button(QDialogButtonBox.Apply):
self.on_applyButton_clicked()
elif button == self.buttonBox.button(QDialogButtonBox.Reset):
self.on_resetButton_clicked()
@pyqtSlot()
def on_applyButton_clicked(self):
"""
Private slot called to apply the settings of the current page.
"""
if self.configStack.currentWidget() != self.emptyPage:
page = self.configStack.currentWidget()
savedState = page.saveState()
page.save()
self.preferencesChanged.emit()
if savedState is not None:
page.setState(savedState)
page.polishPage()
@pyqtSlot()
def on_resetButton_clicked(self):
"""
Private slot called to reset the settings of the current page.
"""
if self.configStack.currentWidget() != self.emptyPage:
currentPage = self.configStack.currentWidget()
savedState = currentPage.saveState()
pageName = self.configList.currentItem().getPageName()
self.configStack.removeWidget(currentPage)
if pageName == "editorHighlightingStylesPage":
self.__initLexers()
self.configItems[pageName][-1] = None
self.showConfigurationPageByName(pageName)
if savedState is not None:
self.configStack.currentWidget().setState(savedState)
def getExpandedEntries(self):
"""
Public method to get a list of expanded entries.
@return list of expanded entries (list of string)
"""
return self.__expandedEntries
@pyqtSlot(QTreeWidgetItem)
def on_configList_itemCollapsed(self, item):
"""
Private slot handling a list entry being collapsed.
@param item reference to the collapsed item (QTreeWidgetItem)
"""
pageName = item.data(0, Qt.UserRole)
if pageName in self.__expandedEntries:
self.__expandedEntries.remove(pageName)
@pyqtSlot(QTreeWidgetItem)
def on_configList_itemExpanded(self, item):
"""
Private slot handling a list entry being expanded.
@param item reference to the expanded item (QTreeWidgetItem)
"""
pageName = item.data(0, Qt.UserRole)
if pageName not in self.__expandedEntries:
self.__expandedEntries.append(pageName)
示例3: SqlConnectionWidget
# 需要导入模块: from PyQt5.QtWidgets import QTreeWidget [as 别名]
# 或者: from PyQt5.QtWidgets.QTreeWidget import currentItem [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
#.........这里部分代码省略.........
示例4: SessionsManager
# 需要导入模块: from PyQt5.QtWidgets import QTreeWidget [as 别名]
# 或者: from PyQt5.QtWidgets.QTreeWidget import currentItem [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,
#.........这里部分代码省略.........
示例5: AddToProject
# 需要导入模块: from PyQt5.QtWidgets import QTreeWidget [as 别名]
# 或者: from PyQt5.QtWidgets.QTreeWidget import currentItem [as 别名]
class AddToProject(QDialog):
def __init__(self, pathProjects, parent=None):
#pathProjects must be a list
super(AddToProject, self).__init__(parent)
self.setWindowTitle(_translate("AddToProject", "Add File to Project"))
self.pathSelected = ''
vbox = QVBoxLayout(self)
self._tree = QTreeWidget()
self._tree.header().setHidden(True)
self._tree.setSelectionMode(QTreeWidget.SingleSelection)
self._tree.setAnimated(True)
vbox.addWidget(self._tree)
hbox = QHBoxLayout()
btnAdd = QPushButton(_translate("AddToProject", "Add here!"))
btnCancel = QPushButton(_translate("AddToProject", "Cancel"))
hbox.addWidget(btnCancel)
hbox.addWidget(btnAdd)
vbox.addLayout(hbox)
#load folders
self._root = None
self._loading_items = {}
self.loading_projects(pathProjects)
self._thread_execution = ThreadExecution(
self._thread_load_projects, args=[pathProjects])
self._thread_execution.finished.connect(self._callback_load_project)
self._thread_execution.start()
btnCancel.clicked['bool'].connect(self.close)
btnAdd.clicked['bool'].connect(self._select_path)
def loading_projects(self, projects):
for project in projects:
loadingItem = LoadingItem()
item = loadingItem.add_item_to_tree(project, self._tree,
parent=self)
self._loading_items[project] = item
def _thread_load_projects(self, projects):
structures = []
for pathProject in projects:
folderStructure = file_manager.open_project(pathProject)
structures.append((folderStructure, pathProject))
self._thread_execution.storage_values = structures
def _callback_load_project(self):
structures = self._thread_execution.storage_values
if structures:
for structure, path in structures:
item = self._loading_items.pop(path, None)
if item is not None:
index = self._tree.indexOfTopLevelItem(item)
self._tree.takeTopLevelItem(index)
self._load_project(structure, path)
def _select_path(self):
item = self._tree.currentItem()
if item:
self.pathSelected = item.toolTip(0)
self.close()
def _load_project(self, folderStructure, folder):
if not folder:
return
name = file_manager.get_basename(folder)
item = QTreeWidgetItem(self._tree)
item.setText(0, name)
item.setToolTip(0, folder)
item.setIcon(0, QIcon(resources.IMAGES['tree-folder']))
if folderStructure[folder][1] is not None:
folderStructure[folder][1].sort()
self._load_folder(folderStructure, folder, item)
item.setExpanded(True)
self._root = item
def _load_folder(self, folderStructure, folder, parentItem):
items = folderStructure[folder]
if items[1] is not None:
items[1].sort()
for _file in items[1]:
if _file.startswith('.'):
continue
subfolder = QTreeWidgetItem(parentItem)
subfolder.setText(0, _file)
subfolder.setToolTip(0, os.path.join(folder, _file))
subfolder.setIcon(0, QIcon(resources.IMAGES['tree-folder']))
self._load_folder(folderStructure,
os.path.join(folder, _file), subfolder)
示例6: EditorConfiguration
# 需要导入模块: from PyQt5.QtWidgets import QTreeWidget [as 别名]
# 或者: from PyQt5.QtWidgets.QTreeWidget import currentItem [as 别名]
#.........这里部分代码省略.........
translations.TR_PREFERENCES_EDITOR_CONFIG_END_OF_LINE)
self._checkEndOfLine.setChecked(settings.USE_PLATFORM_END_OF_LINE)
vboxg6.addWidget(self._checkEndOfLine)
self._checkEndAtLastLine = QCheckBox(
translations.TR_PREFERENCES_EDITOR_CONFIG_END_AT_LAST_LINE)
self._checkEndAtLastLine.setChecked(settings.END_AT_LAST_LINE)
vboxg6.addWidget(self._checkEndAtLastLine)
self._checkTrailing = QCheckBox(
translations.TR_PREFERENCES_EDITOR_CONFIG_REMOVE_TRAILING)
self._checkTrailing.setChecked(settings.REMOVE_TRAILING_SPACES)
vboxg6.addWidget(self._checkTrailing)
self._allowWordWrap = QCheckBox(
translations.TR_PREFERENCES_EDITOR_CONFIG_WORD_WRAP)
self._allowWordWrap.setChecked(settings.ALLOW_WORD_WRAP)
vboxg6.addWidget(self._allowWordWrap)
formFeatures.addWidget(group6, 3, 1)
# pack all the groups
vbox.addWidget(container_widget_with_all_preferences)
vbox.addItem(QSpacerItem(0, 10, QSizePolicy.Expanding,
QSizePolicy.Expanding))
self._preferences.savePreferences.connect(self.save)
def _add_code_pep8(self):
item = QTreeWidgetItem()
item.setFlags(item.flags() | Qt.ItemIsEditable)
self._listIgnoreViolations.addTopLevelItem(item)
self._listIgnoreViolations.setCurrentItem(item)
self._listIgnoreViolations.editItem(item, 0)
def _remove_code_pep8(self):
index = self._listIgnoreViolations.indexOfTopLevelItem(
self._listIgnoreViolations.currentItem())
self._listIgnoreViolations.takeTopLevelItem(index)
def _enable_check_inline(self, val):
"""Method that takes a value to enable the inline style checking"""
if val == Qt.Checked:
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)
示例7: Preferences
# 需要导入模块: from PyQt5.QtWidgets import QTreeWidget [as 别名]
# 或者: from PyQt5.QtWidgets.QTreeWidget import currentItem [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,
#.........这里部分代码省略.........
示例8: FontsColors
# 需要导入模块: from PyQt5.QtWidgets import QTreeWidget [as 别名]
# 或者: from PyQt5.QtWidgets.QTreeWidget import currentItem [as 别名]
class FontsColors(preferences.Page):
def __init__(self, dialog):
super(FontsColors, self).__init__(dialog)
layout = QVBoxLayout()
layout.setContentsMargins(0, 0, 0, 0)
self.setLayout(layout)
self.scheme = SchemeSelector(self)
layout.addWidget(self.scheme)
self.printScheme = QCheckBox()
layout.addWidget(self.printScheme)
hbox = QHBoxLayout()
self.tree = QTreeWidget(self)
self.tree.setHeaderHidden(True)
self.tree.setAnimated(True)
self.stack = QStackedWidget(self)
hbox.addWidget(self.tree)
hbox.addWidget(self.stack)
layout.addLayout(hbox)
hbox = QHBoxLayout()
self.fontLabel = QLabel()
self.fontChooser = QFontComboBox()
self.fontSize = QDoubleSpinBox()
self.fontSize.setRange(6.0, 32.0)
self.fontSize.setSingleStep(0.5)
self.fontSize.setDecimals(1)
hbox.addWidget(self.fontLabel)
hbox.addWidget(self.fontChooser, 1)
hbox.addWidget(self.fontSize)
layout.addLayout(hbox)
# add the items to our list
self.baseColorsItem = i = QTreeWidgetItem()
self.tree.addTopLevelItem(i)
self.defaultStylesItem = i = QTreeWidgetItem()
self.tree.addTopLevelItem(i)
self.defaultStyles = {}
for name in textformats.defaultStyles:
self.defaultStyles[name] = i = QTreeWidgetItem()
self.defaultStylesItem.addChild(i)
i.name = name
self.defaultStylesItem.setExpanded(True)
self.allStyles = {}
for group, styles in ly.colorize.default_mapping():
i = QTreeWidgetItem()
children = {}
self.allStyles[group] = (i, children)
self.tree.addTopLevelItem(i)
i.group = group
for name, base, clss in styles:
j = QTreeWidgetItem()
j.name = name
j.base = base
i.addChild(j)
children[name] = j
self.baseColorsWidget = BaseColors(self)
self.customAttributesWidget = CustomAttributes(self)
self.emptyWidget = QWidget(self)
self.stack.addWidget(self.baseColorsWidget)
self.stack.addWidget(self.customAttributesWidget)
self.stack.addWidget(self.emptyWidget)
self.tree.currentItemChanged.connect(self.currentItemChanged)
self.tree.setCurrentItem(self.baseColorsItem)
self.scheme.currentChanged.connect(self.currentSchemeChanged)
self.scheme.changed.connect(self.changed)
self.baseColorsWidget.changed.connect(self.baseColorsChanged)
self.customAttributesWidget.changed.connect(self.customAttributesChanged)
self.fontChooser.currentFontChanged.connect(self.fontChanged)
self.fontSize.valueChanged.connect(self.fontChanged)
self.printScheme.clicked.connect(self.printSchemeChanged)
app.translateUI(self)
def translateUI(self):
self.printScheme.setText(_("Use this scheme for printing"))
self.fontLabel.setText(_("Font:"))
self.baseColorsItem.setText(0, _("Base Colors"))
self.defaultStylesItem.setText(0, _("Default Styles"))
self.defaultStyleNames = defaultStyleNames()
self.allStyleNames = allStyleNames()
for name in textformats.defaultStyles:
self.defaultStyles[name].setText(0, self.defaultStyleNames[name])
for group, styles in ly.colorize.default_mapping():
try:
n = self.allStyleNames[group][0]
except KeyError:
n = group
self.allStyles[group][0].setText(0, n)
for name, base, clss in styles:
try:
#.........这里部分代码省略.........
示例9: Shortcuts
# 需要导入模块: from PyQt5.QtWidgets import QTreeWidget [as 别名]
# 或者: from PyQt5.QtWidgets.QTreeWidget import currentItem [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
#.........这里部分代码省略.........
示例10: Preferences
# 需要导入模块: from PyQt5.QtWidgets import QTreeWidget [as 别名]
# 或者: from PyQt5.QtWidgets.QTreeWidget import currentItem [as 别名]
class Preferences(QDialog):
configuration = {}
weight = 0
# Signals
savePreferences = pyqtSignal()
def __init__(self, parent=None):
super().__init__(parent, Qt.Dialog)
self.setWindowTitle(translations.TR_PREFERENCES_TITLE)
self.setMinimumSize(900, 650)
box = QVBoxLayout(self)
box.setContentsMargins(3, 3, 3, 3)
self.setAutoFillBackground(True)
# Header
self._header_label = QLabel("")
header_font = self._header_label.font()
header_font.setBold(True)
header_font.setPointSize(header_font.pointSize() + 4)
self._header_label.setFont(header_font)
hbox = QHBoxLayout()
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().setSectionResizeMode(
0, QHeaderView.ResizeToContents)
self.tree.setFixedWidth(200)
hbox.addWidget(self.tree)
self.stacked = QStackedLayout()
header_layout = QVBoxLayout()
header_layout.setContentsMargins(0, 0, 0, 0)
header_layout.addWidget(self._header_label)
header_layout.addLayout(self.stacked)
hbox.addLayout(header_layout)
box.addLayout(hbox)
# Footer buttons
button_box = QDialogButtonBox(
QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
box.addWidget(button_box)
# Connections
button_box.rejected.connect(self.close)
button_box.accepted.connect(self._save_preferences)
self.tree.selectionModel().currentRowChanged.connect(
self._change_current)
self.load_ui()
@pyqtSlot()
def _save_preferences(self):
self.savePreferences.emit()
self.close()
def load_ui(self):
sections = sorted(
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(
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()
self.tree.setCurrentIndex(self.tree.model().index(0, 0))
def _change_current(self):
item = self.tree.currentItem()
index = item.data(0, Qt.UserRole)
#.........这里部分代码省略.........