为了自动化,您必须覆盖 QStyledItemDelegate 的 initStyleOption() 方法,并将假启用与新角色相关联:
#include <QtWidgets>
enum FakeRoles {
FakeEnableRole = Qt::UserRole + 1000
};
class ForegroundDelegate: public QStyledItemDelegate
{
public:
using QStyledItemDelegate::QStyledItemDelegate;
protected:
void initStyleOption(QStyleOptionViewItem *option, const QModelIndex &index) const override{
QStyledItemDelegate::initStyleOption(option, index);
QVariant val = index.data(FakeRoles::FakeEnableRole);
if(val.canConvert<bool>()){
bool enabled = val.value<bool>();
option->palette.setBrush(QPalette::Text,
QApplication::palette().color(enabled ? QPalette::Active:
QPalette::Disabled, QPalette::Text));
}
}
};
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QTableWidget w(4, 4);
ForegroundDelegate *delegate = new ForegroundDelegate(&w);
w.setItemDelegate(delegate);
for(int i=0; i< w.rowCount(); ++i)
for (int j=0; j< w.columnCount(); ++j) {
QTableWidgetItem *it = new QTableWidgetItem(QString("%1-%2").arg(i).arg(j));
w.setItem(i, j, it);
bool enabled = QRandomGenerator::global()->bounded(0, 2) == 0;
it->setData(FakeRoles::FakeEnableRole, enabled);
}
w.show();
QTimer::singleShot(1000, [](){
QPalette pal = QApplication::palette();
pal.setColor(QPalette::Active, QPalette::Text, QColor("salmon"));
pal.setColor(QPalette::Disabled, QPalette::Text, QColor("cyan"));
QApplication::setPalette(pal);
});
return a.exec();
}