You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Qt的QTableView中隐藏/模糊显示密码?

在Qt QTableView中隐藏/模糊显示密码列的正确实现

一、直接隐藏密码列

你之前的代码是拼写错误,正确的方法是调用setColumnHidden(注意大小写,原代码中setColumnhidden的h应该大写),示例代码:

// 隐藏索引为8的列(注意Qt列索引从0开始,需确认目标列的正确索引)
ui->tableView->setColumnHidden(8, true);

二、模糊显示密码(用掩码字符替代明文)

如果不想完全隐藏列,而是将密码显示为*这类掩码字符,需要自定义QStyledItemDelegate来实现:

1. 自定义密码委托类

#include <QStyledItemDelegate>
#include <QPainter>
#include <QLineEdit>

class PasswordDelegate : public QStyledItemDelegate
{
    Q_OBJECT
public:
    explicit PasswordDelegate(QObject *parent = nullptr) : QStyledItemDelegate(parent) {}

    // 重写paint方法,将明文替换为等长掩码
    void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const override
    {
        QStyleOptionViewItem opt = option;
        // 用*替换所有密码字符,也可以换成其他掩码字符
        opt.text = QString(index.data().toString().length(), '*');
        QStyledItemDelegate::paint(painter, opt, index);
    }

    // 若需要编辑时使用密码输入框,重写此方法
    QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const override
    {
        QLineEdit *editor = new QLineEdit(parent);
        editor->setEchoMode(QLineEdit::Password);
        return editor;
    }
};

2. 为目标列设置委托

// 实例化委托并绑定到第8列
PasswordDelegate *pwdDelegate = new PasswordDelegate(this);
ui->tableView->setItemDelegateForColumn(8, pwdDelegate);

注意事项

  • 确认列索引:Qt中QTableView的列索引从0开始,若你的"第8列"是从1开始计数,实际索引应为7,需根据自己的表格结构调整。
  • 若不需要编辑功能,可只保留paint方法的重写;需要编辑时密码输入的场景,再加上createEditor的实现。

内容的提问来源于stack exchange,提问作者Pixal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 18:50:25