【问题标题】:QTableWidget with a masked password column带有屏蔽密码列的 QTableWidget
【发布时间】:2020-12-03 14:55:17
【问题描述】:

是否可以在我使用 PyQt5 创建的 QTableWidget 中屏蔽包含密码或列的某些单元格。我在这里找不到任何选项,搜索也没有找到任何解决方案。

【问题讨论】:

标签: python pyqt5 qtablewidget


【解决方案1】:

一种可能的解决方案是通过委托更改显示的文本:

from PyQt5 import QtWidgets


class PasswordDelegate(QtWidgets.QStyledItemDelegate):
    def initStyleOption(self, option, index):
        super().initStyleOption(option, index)
        if index.column() == 0:
            style = option.widget.style() or QtWidgets.QApplication.style()
            hint = style.styleHint(QtWidgets.QStyle.SH_LineEdit_PasswordCharacter)
            option.text = chr(hint) * len(option.text)


def main():
    import sys

    app = QtWidgets.QApplication(sys.argv)
    view = QtWidgets.QTableWidget(10, 4)
    delegate = PasswordDelegate(view)
    view.setItemDelegate(delegate)
    for i in range(view.rowCount()):
        it = QtWidgets.QTableWidgetItem()
        it.setText("password-{}".format(i))
        view.setItem(i, 0, it)
    view.show()
    view.resize(640, 480)
    sys.exit(app.exec_())


if __name__ == "__main__":
    main()

【讨论】:

    【解决方案2】:

    感谢@eyllanesc 的分享,我实际上能够在我的 tableview 和其他地方的特定列上重用它

    class PasswordDelegate(QtWidgets.QStyledItemDelegate):
        def initStyleOption(self, option, index):
            super().initStyleOption(option, index)
            style = option.widget.style() or QtWidgets.QApplication.style()
            hint = style.styleHint(QtWidgets.QStyle.SH_LineEdit_PasswordCharacter)
            option.text = chr(hint) * len(option.text)
    

    这使得我不必对类中的列进行硬编码,只需将委托应用于我希望它适用的 tableview 或模型中的特定列。通过setItemDelegateForColumn查看更多关于here的信息

    self.password_delegate = PasswordDelegate()
    self.tableView_connections.setItemDelegateForColumn(4, self.password_delegate)
    

    【讨论】:

      猜你喜欢
      • 2015-10-02
      • 2011-02-01
      • 2011-06-04
      • 1970-01-01
      • 2012-07-25
      • 1970-01-01
      • 2016-01-21
      • 2017-10-02
      • 2018-04-25
      相关资源
      最近更新 更多