QStyledItemDelegate::paint - 为什么我的文本没有正确对齐?

6
我正在尝试使用Qt,并希望根据模型的值以自定义文本颜色显示模型。这是渲染为彩色的可选设置,因此我想避免在我的模型中使用Qt :: ForegroundRole,而是在QStyledItemDelegate中实现它。在下面的示例中,我调用QStyledDelegate :: paint,然后继续使用painter-> drawText以红色绘制相同文本的另一个副本。 我的期望是它们应该完美地重叠,但实际上在使用QStyledDelete :: paint时,文本周围似乎有一个边距。

这里是一个更好地展示我所说的内容的图片链接:

enter image description here

现在是一些相关的源代码。
mainwindow.cpp包含:

MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    ui->treeView->setItemDelegate(new TestDelegate());

    QStandardItemModel *model = new QStandardItemModel(this);
    ui->treeView->setModel(model);

    QList<QStandardItem*> items;
    items << new QStandardItem("Moose")
          << new QStandardItem("Goat")
          << new QStandardItem("Llama");

    model->appendRow(items);
}

testdelegate.cpp 包含如下内容:

void TestDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    QStyledItemDelegate::paint(painter, option, index);
    if (index.data().toString() == "Goat") {
        painter->save();
        painter->setPen(Qt::red);
        painter->drawText(option.rect, option.displayAlignment, index.data().toString());
        painter->restore();
    }
}

这种行为在我的运行Qt 4.8.x的Windows 7和Linux Mint测试盒子下都会发生。在两个系统下,文本边距似乎都是x+3,y+1;然而,我担心这可能与字体有关,不希望硬编码偏移量可能会破坏事物。

有什么想法吗?

1个回答

4

option.rect 是项视图单元格的边界矩形,因此它不包含任何边距。您需要的偏移量可以通过从当前的QStyle查询子元素矩形来获取:

...
QStyle* style = QApplication::style();
QRect textRect = style->subElementRect(QStyle::SE_ItemViewItemText, &option);
...
painter->drawText(textRect, option.displayAlignment, index.data().toString());

然而,是否实现它完全取决于当前的QStyle。当我在Linux/Gnome上尝试在我的应用程序中使用Qt v4.8时,它是错误的,实际上在Qt源代码中未实现。因此,我不得不硬编码偏移量,对我来说并不那么糟糕,因为我打算编写自己的QStyle - 你可能没有这么“幸运”。


经过一番尝试,我使用以下代码使其正常工作:QStyleOptionViewItemV4 opt = option; initStyleOption(&opt, index); opt.palette.setBrush(QPalette::Text, QBrush(Qt::red)); opt.widget->style()->drawControl(QStyle::CE_ItemViewItem, &opt, painter);可以使用 opt.widget->style() 代替 QApplication::style(),以避免包含 QApplication。(对于格式不正确的评论表示歉意。) - Random Llama
这并不是同一件事。你询问了如何在项视图项目绘制文本,然而你只是简单地绘制了一个带有彩色元素的项视图项目(这可以使用适当的颜色角色从模型中完成 - 不需要自定义委托)。 - cmannett85

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接