直截了当:我如何获得一个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
最佳答案
您必须覆盖委托人的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)
关于python - QTreeWidgetItems和QLineEdit回显模式,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53974004/