要点:如何获得QTreeWidgetItem以尊重QLineEdits setEchoMode(QLineEdit.Password)?
在过去的一天中,我一直在用头撞墙: 我有一个QTreeWidgetItem的子类(它只是向该类添加了一个额外的字段)
我创建它的一个实例,将其添加到我的TreeWidget中:
twi = DIMTreeWidgetItem.DIMTreeWidgetItem(uuid.uuid4(), [field_name, '<Empty>'])
...
self.ui_instance.main_window.treeWidget.addTopLevelItem(twi)
我根据双击该项目的实例来对其进行编辑:
self.ui_instance.main_window.treeWidget.editItem(项目,列) 效果很好。
我在该列上附加了一个委托,该委托很简单:
def __init__(self, parent=None, *args):
QStyledItemDelegate.__init__(self, parent, *args)
def createEditor(self, parent, option, index):
le = QLineEdit('', parent)
le.setEchoMode(QLineEdit.PasswordEchoOnEdit)
return le
但是,这似乎仅在编辑期间影响项目。对我来说,编辑后遮盖treewidgetitem内容的正确方法是什么?
即使有人可以阐明如何用C ++做到这一点,我相信我也可以将其翻译为pyside2
答案 0 :(得分:1)
您必须覆盖委托人的displayText方法,以使●
字符返回文本长度的很多倍:
from PySide2 import QtCore, QtWidgets
class PasswordDelegate(QtWidgets.QStyledItemDelegate):
def createEditor(self, parent, option, index):
editor = QtWidgets.QLineEdit(parent)
editor.setEchoMode(QtWidgets.QLineEdit.PasswordEchoOnEdit)
return editor
def displayText(self, value, locale):
character = "●" # u"\u25CF"
v = character * len(value)
return super(PasswordDelegate, self).displayText(v, locale)
class EditableItem(QtWidgets.QTreeWidgetItem):
def __init__(self, *args, **kwargs):
super(EditableItem, self).__init__(*args, **kwargs)
self.setFlags(self.flags() | QtCore.Qt.ItemIsEditable)
class MainWindow(QtWidgets.QMainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
tree_widget = QtWidgets.QTreeWidget()
self.setCentralWidget(tree_widget)
for i in range(5):
parent_item = EditableItem(tree_widget, ["{}".format(i)])
for j in range(5):
child_item = EditableItem(["{}-{}".format(i, j)])
parent_item.addChild(child_item)
tree_widget.expandAll()
delegate = PasswordDelegate(tree_widget)
tree_widget.setItemDelegate(delegate)
if __name__ == '__main__':
import sys
app = QtWidgets.QApplication(sys.argv)
w = MainWindow()
w.resize(640, 480)
w.show()
sys.exit(app.exec_())
如果要区分应用哪个元素,则可以覆盖initStyleOption方法,因为它具有与该项目关联的QModelIndex信息,在以下示例中,它将仅应用于具有父元素的元素。
class PasswordDelegate(QtWidgets.QStyledItemDelegate):
def createEditor(self, parent, option, index):
editor = QtWidgets.QLineEdit(parent)
editor.setEchoMode(QtWidgets.QLineEdit.PasswordEchoOnEdit)
return editor
def initStyleOption(self, option, index):
super(PasswordDelegate, self).initStyleOption(option, index)
if index.parent().isValid():
character = "●" # u"\u25CF"
option.text = character * len(option.text)