QTreeView 带有带有浏览按钮的自定义项目委托
QTreeView with custom item delegate with Browse button
使用 Qt5 框架(通过带有 Python 的 pyQt5),我需要创建一个带有参数 - 值列的 QTreeView 小部件,其中某些行的值项必须具有内部 'Browse'按钮打开文件浏览对话框并将所选文件放入相应值的字段中。
阅读有关项目委托的 Qt 手册,我整理了以下代码:
自定义浏览编辑class(QLineEdit + 浏览操作)
class BrowseEdit(QtWidgets.QLineEdit):
def __init__(self, contents='', filefilters=None,
btnicon=None, btnposition=None,
opendialogtitle=None, opendialogdir=None, parent=None):
super().__init__(contents, parent)
self.filefilters = filefilters or _('All files (*.*)')
self.btnicon = btnicon or 'folder-2.png'
self.btnposition = btnposition or QtWidgets.QLineEdit.TrailingPosition
self.opendialogtitle = opendialogtitle or _('Select file')
self.opendialogdir = opendialogdir or os.getcwd()
self.reset_action()
def _clear_actions(self):
for act_ in self.actions():
self.removeAction(act_)
def reset_action(self):
self._clear_actions()
self.btnaction = QtWidgets.QAction(QtGui.QIcon(f"{ICONFOLDER}/{self.btnicon}"), '')
self.btnaction.triggered.connect(self.on_btnaction)
self.addAction(self.btnaction, self.btnposition)
#self.show()
@QtCore.pyqtSlot()
def on_btnaction(self):
selected_path = QtWidgets.QFileDialog.getOpenFileName(self.window(), self.opendialogtitle, self.opendialogdir, self.filefilters)
if not selected_path[0]: return
selected_path = selected_path[0].replace('/', os.sep)
# THIS CAUSES ERROR ('self' GETS DELETED BEFORE THIS LINE!)
self.setText(selected_path)
QTreeView 的自定义项委托:
class BrowseEditDelegate(QtWidgets.QStyledItemDelegate):
def __init__(self, model_indices=None, thisparent=None,
**browse_edit_kwargs):
super().__init__(thisparent)
self.model_indices = model_indices
self.editor = BrowseEdit(**browse_edit_kwargs)
self.editor.setFrame(False)
def createEditor(self, parent: QtWidgets.QWidget, option: QtWidgets.QStyleOptionViewItem,
index: QtCore.QModelIndex) -> QtWidgets.QWidget:
try:
if self.model_indices and index in self.model_indices:
self.editor.setParent(parent)
return self.editor
else:
return super().createEditor(parent, option, index)
except Exception as err:
print(err)
return None
def setEditorData(self, editor, index: QtCore.QModelIndex):
if not index.isValid(): return
if self.model_indices and index in self.model_indices:
txt = index.model().data(index, QtCore.Qt.EditRole)
if isinstance(txt, str):
editor.setText(txt)
else:
super().setEditorData(editor, index)
def setModelData(self, editor, model: QtCore.QAbstractItemModel, index: QtCore.QModelIndex):
if self.model_indices and index in self.model_indices:
model.setData(index, editor.text(), QtCore.Qt.EditRole)
else:
super().setModelData(editor, model, index)
def updateEditorGeometry(self, editor, option: QtWidgets.QStyleOptionViewItem,
index: QtCore.QModelIndex):
editor.setGeometry(option.rect)
创建底层模型:
# create tree view
self.tv_plugins_3party = QtWidgets.QTreeView()
# underlying model (2 columns)
self.model_plugins_3party = QtGui.QStandardItemModel(0, 2)
self.model_plugins_3party.setHorizontalHeaderLabels([_('Plugin'), _('Value')])
# first root item and sub-items
item_git = QtGui.QStandardItem(QtGui.QIcon(f"{ICONFOLDER}/git.png"), 'Git')
item_git.setFlags(QtCore.Qt.ItemIsEnabled)
item_1 = QtGui.QStandardItem(_('Enabled'))
item_1.setFlags(QtCore.Qt.ItemIsEnabled)
item_2 = QtGui.QStandardItem('')
item_2.setFlags(QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsEditable)
item_2.setCheckable(True)
item_2.setUserTristate(False)
item_2.setCheckState(QtCore.Qt.Checked)
item_git.appendRow([item_1, item_2])
item_1 = QtGui.QStandardItem(_('Path'))
item_1.setFlags(QtCore.Qt.ItemIsEnabled)
item_2 = QtGui.QStandardItem('')
item_2.setFlags(QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsEditable)
item_git.appendRow([item_1, item_2])
self.model_plugins_3party.appendRow(item_git)
# second root item and sub-items
item_sqlite = QtGui.QStandardItem(QtGui.QIcon(f"{ICONFOLDER}/sqlite.png"), _('SQLite Editor'))
item_sqlite.setFlags(QtCore.Qt.ItemIsEnabled)
item_1 = QtGui.QStandardItem(_('Enabled'))
item_1.setFlags(QtCore.Qt.ItemIsEnabled)
item_2 = QtGui.QStandardItem('')
item_2.setFlags(QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsEditable)
item_2.setCheckable(True)
item_2.setUserTristate(False)
item_2.setCheckState(QtCore.Qt.Checked)
item_sqlite.appendRow([item_1, item_2])
item_1 = QtGui.QStandardItem(_('Path'))
item_1.setFlags(QtCore.Qt.ItemIsEnabled)
item_2 = QtGui.QStandardItem('')
item_2.setFlags(QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsEditable)
item_sqlite.appendRow([item_1, item_2])
item_1 = QtGui.QStandardItem(_('Commands'))
item_1.setFlags(QtCore.Qt.ItemIsEnabled)
item_2 = QtGui.QStandardItem('<db>')
item_2.setFlags(QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsEditable)
item_sqlite.appendRow([item_1, item_2])
self.model_plugins_3party.appendRow(item_sqlite)
# set model
self.tv_plugins_3party.setModel(self.model_plugins_3party)
为可浏览的编辑字段设置项目委托:
# import traceback
try:
indices = []
indices.append(self.model_plugins_3party.index(1, 1,
self.model_plugins_3party.indexFromItem(item_git)))
indices.append(self.model_plugins_3party.index(1, 1,
self.model_plugins_3party.indexFromItem(item_sqlite)))
self.tv_plugins_3party.setItemDelegate(BrowseEditDelegate(indices))
except:
traceback.print_exc(limit=None)
当我通过按编辑器中的浏览按钮调用打开文件对话框并在选择文件后尝试关闭对话框时发生错误。这时候抛出一个异常,说BrowseEdit对象被删除了!
我意识到发生这种情况是因为项目委托在退出编辑模式时(在启动文件浏览对话框时发生)释放了底层编辑器小部件(在我的例子中是 BrowseEdit)。但是我怎样才能避免这种情况呢?
我尝试过的另一件事是使用 QAbstractItemView::setItemDelegateForRow 方法,如下所示:
# install BrowseEditDelegate for rows 2 and 5
self.tv_plugins_3party.setItemDelegateForRow(2, BrowseEditDelegate())
self.tv_plugins_3party.setItemDelegateForRow(5, BrowseEditDelegate())
-- 但此代码会导致未知异常导致应用程序崩溃而没有任何回溯消息。
每个代表不能只有一个唯一的编辑器,原因有二:
- 编辑器可能有更多的活动实例(使用
openPersistentEditor
打开),例如 table 其中一列的每一行都有一个组合框。
- 每次编辑器将其数据提交给模型时,如果它不是持久性编辑器,它就会被销毁。考虑一下,当一个 Qt 对象被分配给一个 python variable/attribute 时,它实际上是一个指向已由 Qt 创建的底层 C++ 对象的指针。这意味着虽然
self.editor
仍然作为 python 对象存在,但它指向一个在代理关闭编辑器时实际删除的对象。
正如函数名所说,createEditor()
创建一个编辑器,所以解决方案是每次调用createEditor()
时创建一个新实例。
更新
不过这里有一个重要的问题:一旦打开对话框,委托编辑器就会失去焦点。对于项目视图,这与单击另一个项目(更改焦点)相同,这将导致数据提交和编辑器销毁。
"simple" 解决方案是在要打开对话框时阻止委托信号(最重要的是 closeEditor()
, which would call destroyEditor()
),然后再解除阻止。
class 浏览编辑(QtWidgets.QLineEdit):
@QtCore.pyqtSlot()
def on_btnaction(自我):
<b>self.delegate.blockSignals(真)</b>
selected_path = QtWidgets.QFileDialog.getOpenFileName(self.window(), self.opendialogtitle, self.opendialogdir, self.filefilters)
<b>self.delegate.blockSignals(假)</b>
如果不是 selected_path[0]:return
selected_path = selected_path[0].replace('/', os.sep)
# 这会导致错误('self' 在此行之前被删除!)
self.setText(selected_path)
class BrowseEditDelegate(QtWidgets.QStyledItemDelegate):
# ...
def createEditor(self, parent: QtWidgets.QWidget, option: QtWidgets.QStyleOptionViewItem,
索引:QtCore.QModelIndex) -> QtWidgets.QWidget:
尝试:
如果 self.model_indices 和 self.model_indices 中的索引:
编辑器 = BrowseEdit(parent=parent)
<b>editor.delegate = 自己</b>
return 编辑器
别的:
return super().createEditor(parent, option, index)
除了异常错误:
打印(错误)
return None
也就是说,这是一个 hack。虽然它 有效 ,但不能保证它会在 Qt 的未来版本中使用,当其他信号可能被引入或它们的行为发生变化时。
更好更优雅的解决方案是创建一个信号,在单击浏览按钮时调用该信号,然后项目视图(或其任何父视图)将负责浏览,如果文件对话框结果有效并再次开始编辑字段:
class BrowseEditDelegate(QtWidgets.QStyledItemDelegate):
<b>已请求浏览 = QtCore.pyqtSignal(QtCore.QModelIndex)</b>
# ...
def createEditor(self, parent: QtWidgets.QWidget, option: QtWidgets.QStyleOptionViewItem,
索引:QtCore.QModelIndex) -> QtWidgets.QWidget:
尝试:
如果 self.model_indices 和 self.model_indices 中的索引:
编辑器 = BrowseEdit(parent=parent)
<b>editor.btnaction.triggered.connect(
拉姆达:self.browseRequested.emit(索引))</b>
return 编辑器
别的:
return super().createEditor(parent, option, index)
除了异常错误:
打印(错误)
return None
class Window(QtWidgets.QWidget):
def __init__(自我):
# ...
delegate = BrowseEditDelegate(指数)
self.tv_plugins_3party.setItemDelegate(代表)
delegate.browseRequested.connect(self.browseRequested)
def browseRequested(自我,索引):
selected_path = QtWidgets.QFileDialog.getOpenFileName(self.window(), 'Select file', index.data())
如果 selected_path[0]:
self.model_plugins_3party.setData(index, selected_path[0])
self.tv_plugins_3party.edit(索引)
使用 Qt5 框架(通过带有 Python 的 pyQt5),我需要创建一个带有参数 - 值列的 QTreeView 小部件,其中某些行的值项必须具有内部 'Browse'按钮打开文件浏览对话框并将所选文件放入相应值的字段中。
阅读有关项目委托的 Qt 手册,我整理了以下代码:
自定义浏览编辑class(QLineEdit + 浏览操作)
class BrowseEdit(QtWidgets.QLineEdit):
def __init__(self, contents='', filefilters=None,
btnicon=None, btnposition=None,
opendialogtitle=None, opendialogdir=None, parent=None):
super().__init__(contents, parent)
self.filefilters = filefilters or _('All files (*.*)')
self.btnicon = btnicon or 'folder-2.png'
self.btnposition = btnposition or QtWidgets.QLineEdit.TrailingPosition
self.opendialogtitle = opendialogtitle or _('Select file')
self.opendialogdir = opendialogdir or os.getcwd()
self.reset_action()
def _clear_actions(self):
for act_ in self.actions():
self.removeAction(act_)
def reset_action(self):
self._clear_actions()
self.btnaction = QtWidgets.QAction(QtGui.QIcon(f"{ICONFOLDER}/{self.btnicon}"), '')
self.btnaction.triggered.connect(self.on_btnaction)
self.addAction(self.btnaction, self.btnposition)
#self.show()
@QtCore.pyqtSlot()
def on_btnaction(self):
selected_path = QtWidgets.QFileDialog.getOpenFileName(self.window(), self.opendialogtitle, self.opendialogdir, self.filefilters)
if not selected_path[0]: return
selected_path = selected_path[0].replace('/', os.sep)
# THIS CAUSES ERROR ('self' GETS DELETED BEFORE THIS LINE!)
self.setText(selected_path)
QTreeView 的自定义项委托:
class BrowseEditDelegate(QtWidgets.QStyledItemDelegate):
def __init__(self, model_indices=None, thisparent=None,
**browse_edit_kwargs):
super().__init__(thisparent)
self.model_indices = model_indices
self.editor = BrowseEdit(**browse_edit_kwargs)
self.editor.setFrame(False)
def createEditor(self, parent: QtWidgets.QWidget, option: QtWidgets.QStyleOptionViewItem,
index: QtCore.QModelIndex) -> QtWidgets.QWidget:
try:
if self.model_indices and index in self.model_indices:
self.editor.setParent(parent)
return self.editor
else:
return super().createEditor(parent, option, index)
except Exception as err:
print(err)
return None
def setEditorData(self, editor, index: QtCore.QModelIndex):
if not index.isValid(): return
if self.model_indices and index in self.model_indices:
txt = index.model().data(index, QtCore.Qt.EditRole)
if isinstance(txt, str):
editor.setText(txt)
else:
super().setEditorData(editor, index)
def setModelData(self, editor, model: QtCore.QAbstractItemModel, index: QtCore.QModelIndex):
if self.model_indices and index in self.model_indices:
model.setData(index, editor.text(), QtCore.Qt.EditRole)
else:
super().setModelData(editor, model, index)
def updateEditorGeometry(self, editor, option: QtWidgets.QStyleOptionViewItem,
index: QtCore.QModelIndex):
editor.setGeometry(option.rect)
创建底层模型:
# create tree view
self.tv_plugins_3party = QtWidgets.QTreeView()
# underlying model (2 columns)
self.model_plugins_3party = QtGui.QStandardItemModel(0, 2)
self.model_plugins_3party.setHorizontalHeaderLabels([_('Plugin'), _('Value')])
# first root item and sub-items
item_git = QtGui.QStandardItem(QtGui.QIcon(f"{ICONFOLDER}/git.png"), 'Git')
item_git.setFlags(QtCore.Qt.ItemIsEnabled)
item_1 = QtGui.QStandardItem(_('Enabled'))
item_1.setFlags(QtCore.Qt.ItemIsEnabled)
item_2 = QtGui.QStandardItem('')
item_2.setFlags(QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsEditable)
item_2.setCheckable(True)
item_2.setUserTristate(False)
item_2.setCheckState(QtCore.Qt.Checked)
item_git.appendRow([item_1, item_2])
item_1 = QtGui.QStandardItem(_('Path'))
item_1.setFlags(QtCore.Qt.ItemIsEnabled)
item_2 = QtGui.QStandardItem('')
item_2.setFlags(QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsEditable)
item_git.appendRow([item_1, item_2])
self.model_plugins_3party.appendRow(item_git)
# second root item and sub-items
item_sqlite = QtGui.QStandardItem(QtGui.QIcon(f"{ICONFOLDER}/sqlite.png"), _('SQLite Editor'))
item_sqlite.setFlags(QtCore.Qt.ItemIsEnabled)
item_1 = QtGui.QStandardItem(_('Enabled'))
item_1.setFlags(QtCore.Qt.ItemIsEnabled)
item_2 = QtGui.QStandardItem('')
item_2.setFlags(QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsEditable)
item_2.setCheckable(True)
item_2.setUserTristate(False)
item_2.setCheckState(QtCore.Qt.Checked)
item_sqlite.appendRow([item_1, item_2])
item_1 = QtGui.QStandardItem(_('Path'))
item_1.setFlags(QtCore.Qt.ItemIsEnabled)
item_2 = QtGui.QStandardItem('')
item_2.setFlags(QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsEditable)
item_sqlite.appendRow([item_1, item_2])
item_1 = QtGui.QStandardItem(_('Commands'))
item_1.setFlags(QtCore.Qt.ItemIsEnabled)
item_2 = QtGui.QStandardItem('<db>')
item_2.setFlags(QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsEditable)
item_sqlite.appendRow([item_1, item_2])
self.model_plugins_3party.appendRow(item_sqlite)
# set model
self.tv_plugins_3party.setModel(self.model_plugins_3party)
为可浏览的编辑字段设置项目委托:
# import traceback
try:
indices = []
indices.append(self.model_plugins_3party.index(1, 1,
self.model_plugins_3party.indexFromItem(item_git)))
indices.append(self.model_plugins_3party.index(1, 1,
self.model_plugins_3party.indexFromItem(item_sqlite)))
self.tv_plugins_3party.setItemDelegate(BrowseEditDelegate(indices))
except:
traceback.print_exc(limit=None)
当我通过按编辑器中的浏览按钮调用打开文件对话框并在选择文件后尝试关闭对话框时发生错误。这时候抛出一个异常,说BrowseEdit对象被删除了!
我意识到发生这种情况是因为项目委托在退出编辑模式时(在启动文件浏览对话框时发生)释放了底层编辑器小部件(在我的例子中是 BrowseEdit)。但是我怎样才能避免这种情况呢?
我尝试过的另一件事是使用 QAbstractItemView::setItemDelegateForRow 方法,如下所示:
# install BrowseEditDelegate for rows 2 and 5
self.tv_plugins_3party.setItemDelegateForRow(2, BrowseEditDelegate())
self.tv_plugins_3party.setItemDelegateForRow(5, BrowseEditDelegate())
-- 但此代码会导致未知异常导致应用程序崩溃而没有任何回溯消息。
每个代表不能只有一个唯一的编辑器,原因有二:
- 编辑器可能有更多的活动实例(使用
openPersistentEditor
打开),例如 table 其中一列的每一行都有一个组合框。 - 每次编辑器将其数据提交给模型时,如果它不是持久性编辑器,它就会被销毁。考虑一下,当一个 Qt 对象被分配给一个 python variable/attribute 时,它实际上是一个指向已由 Qt 创建的底层 C++ 对象的指针。这意味着虽然
self.editor
仍然作为 python 对象存在,但它指向一个在代理关闭编辑器时实际删除的对象。
正如函数名所说,createEditor()
创建一个编辑器,所以解决方案是每次调用createEditor()
时创建一个新实例。
更新
不过这里有一个重要的问题:一旦打开对话框,委托编辑器就会失去焦点。对于项目视图,这与单击另一个项目(更改焦点)相同,这将导致数据提交和编辑器销毁。
"simple" 解决方案是在要打开对话框时阻止委托信号(最重要的是 closeEditor()
, which would call destroyEditor()
),然后再解除阻止。
class 浏览编辑(QtWidgets.QLineEdit):
@QtCore.pyqtSlot()
def on_btnaction(自我):
<b>self.delegate.blockSignals(真)</b>
selected_path = QtWidgets.QFileDialog.getOpenFileName(self.window(), self.opendialogtitle, self.opendialogdir, self.filefilters)
<b>self.delegate.blockSignals(假)</b>
如果不是 selected_path[0]:return
selected_path = selected_path[0].replace('/', os.sep)
# 这会导致错误('self' 在此行之前被删除!)
self.setText(selected_path)
class BrowseEditDelegate(QtWidgets.QStyledItemDelegate):
# ...
def createEditor(self, parent: QtWidgets.QWidget, option: QtWidgets.QStyleOptionViewItem,
索引:QtCore.QModelIndex) -> QtWidgets.QWidget:
尝试:
如果 self.model_indices 和 self.model_indices 中的索引:
编辑器 = BrowseEdit(parent=parent)
<b>editor.delegate = 自己</b>
return 编辑器
别的:
return super().createEditor(parent, option, index)
除了异常错误:
打印(错误)
return None
也就是说,这是一个 hack。虽然它 有效 ,但不能保证它会在 Qt 的未来版本中使用,当其他信号可能被引入或它们的行为发生变化时。
更好更优雅的解决方案是创建一个信号,在单击浏览按钮时调用该信号,然后项目视图(或其任何父视图)将负责浏览,如果文件对话框结果有效并再次开始编辑字段:
class BrowseEditDelegate(QtWidgets.QStyledItemDelegate):
<b>已请求浏览 = QtCore.pyqtSignal(QtCore.QModelIndex)</b>
# ...
def createEditor(self, parent: QtWidgets.QWidget, option: QtWidgets.QStyleOptionViewItem,
索引:QtCore.QModelIndex) -> QtWidgets.QWidget:
尝试:
如果 self.model_indices 和 self.model_indices 中的索引:
编辑器 = BrowseEdit(parent=parent)
<b>editor.btnaction.triggered.connect(
拉姆达:self.browseRequested.emit(索引))</b>
return 编辑器
别的:
return super().createEditor(parent, option, index)
除了异常错误:
打印(错误)
return None
class Window(QtWidgets.QWidget):
def __init__(自我):
# ...
delegate = BrowseEditDelegate(指数)
self.tv_plugins_3party.setItemDelegate(代表)
delegate.browseRequested.connect(self.browseRequested)
def browseRequested(自我,索引):
selected_path = QtWidgets.QFileDialog.getOpenFileName(self.window(), 'Select file', index.data())
如果 selected_path[0]:
self.model_plugins_3party.setData(index, selected_path[0])
self.tv_plugins_3party.edit(索引)