gpt4 book ai didi

python - QTreeWidgetItems 和 QLineEdit 回显模式

转载 作者:行者123 更新时间:2023-12-01 08:29:39 28 4
gpt4 key购买 nike

重点:如何让 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(项目,列)这工作得很好。

我有一个委托(delegate)附加到该列,它很简单:

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

最佳答案

您必须覆盖委托(delegate)的 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)

enter image description here

关于python - QTreeWidgetItems 和 QLineEdit 回显模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53974004/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com