簡體   English   中英

如何在QTableView中為特定單元格着色或使文本變為粗體?

[英]How to color or make text bold for particular cell in QTableView?

我已經使用QTableView來查看我的Qt程序中的表格數據,並且我需要將某些單元格區別於其他單元格,可以在這些特定單元格中繪制字體粗體或繪制這些特定單元格的背景。

有人可以提供代碼,而不僅僅是說使用QAbstractItemDelegate嗎?

我閱讀了QAbstractItemDelegate文檔,但無法理解,請使用示例進行解釋。

為了使文本在表​​視圖中以不同方式顯示,您可以修改模型(如果存在),並在模型的QAbstractItemModel::data()函數中處理Qt::FontRole和/或Qt::ForegroundRole角色。 例如:

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 {
        [..]
    }

}

無需使用抽象委托。 Styled delegate完成了您需要的大部分工作。 使用它並重新實現只需要的行為。

。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:

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
}

然后將委托應用於視圖。 如果shouldBeBold()返回false,則委托將繪制為標准的。 如果返回true,則將應用粗體字體。

我希望你能夠開始。

如果您沒有模型或委托,並且您不想創建模型或委托,則可以直接設置單元格的字體:

QFont font(cell->font());
font.setBold(true);
cell->setFont(font);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM