这很简单:我想要模拟一个项目的颜色变化被禁用而不是禁用它。
有了QTableWidgetItem和QStandardItem项,我使用的代码如下
item->setForeground( enabled ? QApplication::palette().color( QPalette::Text ) : QApplication::palette().color( QPalette::Disabled, QPalette::Text ) );现在就来。但是,如果用户使用新的调色板调用QApplication::setPalette( ... ),则必须手动刷新该项。我更愿意设置一个ColorGroup和Role,这样Qt就知道如何刷新。这样做有可能吗?
发布于 2019-04-11 02:54:56
要实现自动化,您必须覆盖QStyledItemDelegate的initStyleOption()方法,并将假enable与新角色关联:
#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();
}https://stackoverflow.com/questions/55617335
复制相似问题