Qt::BackgroundRole seems to be ignored

不想你离开。 提交于 2019-12-10 19:10:16

问题


I'm using a custom table model derived from QAbstractTableModel.

I've overwritter headerData() and I can change the font color for individual row-headers (or column-header, but I'm all about rows here) by returning the color on Qt::ForegroundRole

if(role == Qt::ForegroundRole)
   return Qt::green;

But if I go for Qt::BackgroundRole to set the background color of the header cells, nothing happens.

if(role == Qt::BackgroundRole)
   return Qt::red;

I set a breakpoint on the return and it is reached. But nothing happens :-(

Any ideas on where I'm wrong?


回答1:


AFAIK the role colours are equivalent to setting a palette colour, the QStyle drawing the header cells is free to ignore it.

I've had trouble using QPalette or style sheets to set arbitrary colours on widgets. Text tends to work, as do 'window' coloured backgrounds (a QPushButton background for example), but text entry field backgrounds don't (QLineEdit for example). But AFAIK it's down to the particular QStyle implementation, so will vary not only across widgets, but also across platforms. The only certain way to get things exactly how you want is to reimplement QStyle (a big job), or paint it manually in paintEvent(..) (difficult to follow the current QStyle and still lots of code).




回答2:


1) You can also achieve it by using own item delegates - inherit from QStyledItemDelegate or whatever else, reimplement one method and set it to view.

2) For specific table or header view, use style that respects brushes:

//auto keys = QStyleFactory::keys();
if(auto style = QStyleFactory::create("Fusion")) {
    verticalHeader()->setStyle(style);
}


来源:https://stackoverflow.com/questions/13837403/qtbackgroundrole-seems-to-be-ignored

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!