Custom QTableWidgetItem
-
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?PS:
/********************************************** .h */ #ifndef WIDGET_ITEM_H #define WIDGET_ITEM_H #include "config.h" #include <QTableWidgetItem> #include <QVariant> #include <QString> #include <QDataStream> class WidgetItem : public QTableWidgetItem { public: WidgetItem(); virtual QVariant data(int role) const; virtual void setData(int role, const QVariant &value); private: QString m_realText; QString m_echoText; }; #endif // WIDGET_ITEM_H
/********************************************** .cpp */ #include "widget_item.h" WidgetItem::WidgetItem() : QTableWidgetItem() { } QVariant WidgetItem::data(int role) const { Q_UNUSED(role); 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); }
-
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: http://doc.qt.io/qt-5/qt.html#ItemDataRole-enum
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{ Q_OBJECT Q_DISABLE_COPY(PwdDelegate) public: explicit PwdDelegate(QObject *parent = Q_NULLPTR) : QStyledItemDelegate(parent), passwordChar(QApplication::style()->styleHint(QStyle::SH_LineEdit_PasswordCharacter)) {} QString displayText(const QVariant &value, const QLocale &locale) const Q_DECL_OVERRIDE{ return QString(QStyledItemDelegate::displayText(value,locale).size(), passwordChar); } private: const QChar passwordChar; };
Now you can use
tableWidget->setItemDelegateForColumn(4, new PwdDelegate(tableWidget));