Important: Please read the Qt Code of Conduct -

Custom QTableWidgetItem

  • 0_1545295384996_2.gif

    I want the QTableWidgetItem's text' s echoMode to PassWord just like QLineEdit's function setEchoMode(Qt::PassWord);, so I customed the QTableWidgetItem( I know QLineEdit can solve my problem, but I want to use QTableWidgetItem to implement it. ).

    So, I wrote the codes just as the upper gif picture shows.

    But, now, there are two problem puzzling me at this phenomenon.

    One, why text echotext not to set the item's text?
    Two, why is there an extra widget just like QCheckBox in this item's left part?


    /********************************************** .h */
    #ifndef WIDGET_ITEM_H
    #define WIDGET_ITEM_H
    #include "config.h"
    #include <QTableWidgetItem>
    #include <QVariant>
    #include <QString>
    #include <QDataStream>
    class WidgetItem : public QTableWidgetItem
        virtual QVariant data(int role) const;
        virtual void setData(int role, const QVariant &value);
        QString m_realText;
        QString m_echoText;
    #endif // WIDGET_ITEM_H
    /********************************************** .cpp */
    #include "widget_item.h"
    WidgetItem::WidgetItem() : QTableWidgetItem()
    QVariant WidgetItem::data(int role) const
        return QVariant(m_realText);
    void WidgetItem::setData(int role, const QVariant& value)
        m_echoText = m_realText = value.toString();
        //m_echoText.replace(0, m_echoText.size(), QChar('.'));
        m_echoText = "echotext";
        QTableWidgetItem::setData(role, m_echoText);

  • Qt Champions 2019

    You're returning m_realText for every given role - this is for sure not what you really want. Please take a look at the different roles:
    The same goes for setData()

  • You don't need a custom QTableWidgetItem. The model should not care about how items are represented.
    What you want is a custom delegate:

    class PwdDelegate : public : QStyledItemDelegate{
        explicit PwdDelegate(QObject *parent = Q_NULLPTR) 
            : QStyledItemDelegate(parent),
        QString displayText(const QVariant &value, const QLocale &locale) const Q_DECL_OVERRIDE{
            return QString(QStyledItemDelegate::displayText(value,locale).size(), passwordChar);
        const QChar passwordChar;

    Now you can use tableWidget->setItemDelegateForColumn(4, new PwdDelegate(tableWidget));

  • @VRonin Yes, you are right. Thanks a lot..

Log in to reply