C++ 为什么我的文本没有正确对齐?

C++ 为什么我的文本没有正确对齐?,c++,qt,C++,Qt,我给了Qt一个机会,希望有一个基于其值的自定义文本颜色的模型显示。这是一个可选设置,可以用颜色渲染它,因此我希望避免在模型中使用Qt::ForegroundRole,而是在QStyledItemDelegate中实现它。在下面的示例中,我调用QStyledDelegate::paint,然后继续使用painter->drawText以红色绘制相同文本的附加副本。我的期望是它们应该完美地覆盖,而实际上,在使用QStyledDelete::paint时,文本周围似乎有一个空白 这里有一个图片链接,可

我给了Qt一个机会,希望有一个基于其值的自定义文本颜色的模型显示。这是一个可选设置,可以用颜色渲染它,因此我希望避免在模型中使用Qt::ForegroundRole,而是在QStyledItemDelegate中实现它。在下面的示例中,我调用
QStyledDelegate::paint
,然后继续使用
painter->drawText
以红色绘制相同文本的附加副本。我的期望是它们应该完美地覆盖,而实际上,在使用
QStyledDelete::paint
时,文本周围似乎有一个空白

这里有一个图片链接,可以更好地显示我所说的内容:

现在查看一些相关的源代码。
main窗口。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);
}
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();
    }
}
上述行为发生在运行Qt4.8.x的Windows7和LinuxMint测试盒下。两种系统下的文本边距均为x+3,y+1;然而,我担心这可能与字体有关,不希望硬编码偏移量可能会破坏某些东西


有什么想法吗?

选项。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上尝试将它与QtV4.8一起用于我的应用程序时,它是错误的,并且确实没有在Qt源代码中实现。所以我不得不硬编码偏移量,对我来说,这并不像我打算写我自己的
QStyle
-你可能没那么“幸运”。

经过一段时间的努力,我用以下方法实现了这一点:
QStyleOptionViewItemV4 opt=option;initStyleOption(&opt,index);setBrush(qpalete::Text,QBrush(Qt::red));QApplication::style()->drawControl(QStyle::CE_ItemViewItem,&opt,painter)
代替
QApplication::syle()
opt.widget->style()
也可以用来阻止QApplication include。(很抱歉未能格式化此评论。)这不是一回事。您询问了项目视图项目将在何处绘制文本,而您只是使用彩色元素绘制了项目视图项目(可以使用适当的颜色角色从模型中完成此操作-无需自定义代理)。