密码保护 QstandardItem pyqt5

password protect QstandardItem pyqt5

我有一个包含密码的 QstandardItem,我想将此 QstandardItem 的值屏蔽为密码或一堆 ******,即使您正在编辑该列。

username = QStandardItem("%s" % ("username"))
password = QStandardItem("%s" % ("password"))

self.tbViewModel.appendRow([username, password])

我希望用户在 select 密码列和 CTRL+C 时能够复制实际密码。

有没有密码保护 QStandardItem 值的方法?

您可以使用一个角色来指示它是一个密码,并使用一个委托来使用该信息来修改 QLineEdit 中的内容:

PasswordRole = Qt.UserRole + 1
password_item = QStandardItem("password")
password_item.setData(True, PasswordRole)
class PasswordDelegate(QStyledItemDelegate):
    def initStyleOption(self, option, index):
        super().initStyleOption(option, index)
        if index.data(PasswordRole):
            style = option.widget.style() or QApplication.style()
            hint = style.styleHint(QStyle.SH_LineEdit_PasswordCharacter)
            option.text = chr(hint) * len(option.text)

    def createEditor(self, parent, option, index):
        editor = super().createEditor(parent, option, index)
        if index.data(PasswordRole) and isinstance(editor, QLineEdit):
            editor.setEchoMode(QLineEdit.Password)
        return editor
password_delegate = PasswordDelegate(your_view)
your_view.setItemDelegate(password_delegate)