QHeaderView 样式表中使用背景图片
在官档《Qt Style Sheets Reference 》一文中 QHeaderView 的部分有提到:
QHeaderView 支持盒子模型。表头视图的各节使用::section设置子控件样式。
有关示例,请参见自定义QHeaderView。
官档中有提到 子控件 的事情,所以正常情况下表头设置背景图片,会被表头的子控件挡住,只能显示部分。如果要显示全图,就得让表头的子控件的背景色变成透明。
测试代码用例
#include "MainWindow.h"
#include <QtWidgets>
#include "DebugTool.h"
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QString fileName = "sheet1.qss"; // 文件名,如果没有该文件,则会自动创建
loadQssFile (fileName); // DebugTool.h 加载qss文件
watchQssFile (fileName); // DebugTool.h 监测qss变化
QWidget w;
addShortcut (&w,fileName); // DebugTool.h 使用ctrl+q ,ctrl+s 快捷键打开qss文件
auto * vb = new QVBoxLayout(&w);
QTableView *table = new QTableView(&w);
vb->addWidget (table);
QStandardItemModel *hm = new QStandardItemModel(3,3,table);
hm->setHorizontalHeaderLabels ({"h1","h2","h3"});
table->setModel (hm);
table->verticalHeader ()->hide ();
w.show ();
return a.exec();
}
1、正常设置图片
QHeaderView{
font : bold ;
border-image:url(E:/users/desktop/2222.jpg); /*随便找一张测试图片*/
}
2、设置表头子控件的背景色
QHeaderView的子控件 在样式表中使用 ::section 来表示。
添加样式表
QHeaderView{ font : bold ; border-image:url(E:/users/desktop/2222.jpg); } QHeaderView::section{ background-color :transparent; }
3、调整其他属性
背景图片已经能完整显示,但是整体显示效果不明显
3.1)字体颜色改用白色
可以在QHeaderView里提供,如下:
QHeaderView{
color : white;
font : bold ;
border-image:url(E:/users/desktop/2222.jpg);
}
3.2)表头子控件添加边框
QHeaderView::section{
background-color :transparent;
border : 0px; /* 这一步不能少*/
border-right: 1px solid white;
}
这样就可以了
4 更进一步
QHeaderView{
color : white;
font : bold ;
border-image:url(E:/users/desktop/2222.jpg);
}
QHeaderView::section{
background-color :transparent;
border : 0px;
border-right: 1px solid white;
}
QHeaderView::section:checked{
background-color :rgba(0, 200, 200, 180);
}
QHeaderView::section:hover{
background-color :rgba(0, 255, 0, 180);
}