Search code examples
pythonpyqtmaskqlistwidget

Mask text after character in QListWidget


I have a QListWidget and I would like to hide all text after the first : while the full string is still there for me to use, for all the items.

Example:

List item | username:password

What I want:

List Item (Password is still there but hidden) | username

This is just to make the UI cleaner, are there any built in PyQT functions which could help me achieve this or would I have to come up with some other solution using Python? Reproducable example is just a QListWidget with items that have : in them.


Solution

  • One possible solution is to use a delegate:

    import sys
    
    from PyQt5 import QtCore, QtWidgets
    
    
    class Delegate(QtWidgets.QStyledItemDelegate):
        def displayText(self, value, locale):
            text = super().displayText(value, locale)
            separator = ":"
            values = text.split(separator)
            if len(values) == 2:
                username, password = values
                mask_character = chr(
                    QtWidgets.QApplication.style().styleHint(
                        QtWidgets.QStyle.SH_LineEdit_PasswordCharacter
                    )
                )
                return separator.join([username, mask_character * len(password)])
            return text
    
    
    def main():
        app = QtWidgets.QApplication(sys.argv)
    
        w = QtWidgets.QListWidget()
        delegate = Delegate(w)
        w.setItemDelegate(delegate)
        w.show()
    
        for i in range(10):
            text = f"username{i}:password{i}"
            item = QtWidgets.QListWidgetItem(text)
            item.setFlags(item.flags() | QtCore.Qt.ItemIsEditable)
            w.addItem(item)
        sys.exit(app.exec_())
    
    
    if __name__ == "__main__":
        main()