QTreeWidget显示类似QTableWidget网格的实现
先上图看看效果
方案一:QSS
ui->treeWidget->setStyleSheet("QTreeView::item {\
padding - left:5px;\
min - height: 25px;\
border:1px solid lightgray;\
border - left:transparent;\
border - top:transparent;}\
QTreeView::item:selected:active{\
background: rgb(93,180,226);\
color:white;} ");
此方案会导致item->setBackground函数失效,可能是默认了单元格颜色为透明,具体原因博主并未深究,有知道原因的小伙伴也可以留言告诉我
如果需要使用setBackGround函数的小伙伴,可以使用下面一种方法。
方案二:paintEvent
创建从QTreeWidget继承的子类TreeWidgetBase,将UI中的QTreeWidget提升为TreeWidgetBase
void TreeWidgetBase::paintEvent(QPaintEvent* event)
{
QPainter painter(viewport());
painter.setPen(QPen(QColor(192, 192, 192), 1));
QTreeWidgetItemIterator it(this);
while (*it)
{
if ((*it)) {
QRect rtItem = visualItemRect(*it);
if(*it == this->topLevelItem(0)){
painter.drawLine(rtItem.topLeft(), rtItem.topRight());
}
painter.drawLine(rtItem.topRight(), rtItem.bottomRight());
painter.drawLine(rtItem.bottomLeft(), rtItem.bottomRight());
painter.drawLine(rtItem.topLeft(), rtItem.bottomLeft());
QPoint ptStart(rtItem.right(),rtItem.top());
QPoint ptEnd(rtItem.right(),rtItem.bottom());
for(int i = columnCount()-1; i>0;i--){
int colWidth = this->columnWidth(i);
ptStart += QPoint(0- colWidth, 0);
ptEnd += QPoint(0 - colWidth, 0);
painter.drawLine(ptStart, ptEnd);
}
}
++it;
}
QTreeWidget::paintEvent(event);
}
`