[英]How to color or make text bold for particular cell in QTableView?
I have used QTableView
to saw tabular data in my Qt program and somehow I need to differentiate some cells from others, can be done making font bold in those particular cells or painting background of those particular cells. 我已经使用
QTableView
来查看我的Qt程序中的表格数据,并且我需要将某些单元格区别于其他单元格,可以在这些特定单元格中绘制字体粗体或绘制这些特定单元格的背景。
Can someone please provide code rather than just saying use QAbstractItemDelegate
? 有人可以提供代码,而不仅仅是说使用
QAbstractItemDelegate
吗?
I read through documentation of QAbstractItemDelegate
but could not understand so please explain using example. 我阅读了
QAbstractItemDelegate
文档,但无法理解,请使用示例进行解释。
In order to make text appear differently in your table view, you can modify your model, if any exists, and handle Qt::FontRole
and/or Qt::ForegroundRole
roles in the model's QAbstractItemModel::data()
function. 为了使文本在表视图中以不同方式显示,您可以修改模型(如果存在),并在模型的
QAbstractItemModel::data()
函数中处理Qt::FontRole
和/或Qt::ForegroundRole
角色。 For example: 例如:
QVariant MyModel::data(const QModelIndex &index, int role) const
{
if (role == Qt::FontRole && index.column() == 0) { // First column items are bold.
QFont font;
font.setBold(true);
return font;
} else if (role == Qt::ForegroundRole && index.column() == 0) {
return QColor(Qt::red);
} else {
[..]
}
} }
No need to go with abstract delegate. 无需使用抽象委托。 Styled delegate does most of the work you need.
Styled delegate完成了您需要的大部分工作。 Use it and reimplement only needed behaviour.
使用它并重新实现只需要的行为。
.h: 。H:
#include <QStyledItemDelegate>
class MyDelegate : public QStyledItemDelegate
{
Q_OBJECT
public:
explicit MyDelegate(QObject *parent = 0);
void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const;
private:
bool shouldBeBold(const QModelIndex &index);
}
.cpp: 的.cpp:
MyDelegate::MyDelegate(QObject *parent) :
QStyledItemDelegate(parent)
{
}
void MyDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
QStyleOptionViewItem opt = option;
initStyleOption(&opt, index);
QVariant data = index.data(...); // pick the data you need here
opt.font.setBold(shouldBeBold(data));
QStyledItemDelegate::paint(painter, opt, index);
}
bool MyDelegate::shouldBeBold(const QModelIndex &index)
{
// you need to implement this
}
Then apply delegate to the view. 然后将委托应用于视图。 If
shouldBeBold()
returns false, delegate will paint like a standard one. 如果
shouldBeBold()
返回false,则委托将绘制为标准的。 If it returns true, it will apply bold font. 如果返回true,则将应用粗体字体。
I hope that's enought for you to get started. 我希望你能够开始。
If you don't have a model or a delegate and you don't want to create one, you can set the font of the cell directly: 如果您没有模型或委托,并且您不想创建模型或委托,则可以直接设置单元格的字体:
QFont font(cell->font());
font.setBold(true);
cell->setFont(font);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.