QAbstractItemDelegate绘制方法

时间:2015-05-20 15:53:11

标签: qt qt5.4 qtextdocument

我有一个继承QAbstractItemDelegate的类,我在QTextDocument方法中使用paint()。我的模型包含两个项目,但是当我运行我的qt应用程序时,项目将在QListView的第一项中绘制。

CODE

void ProductItemDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option,
                                const QModelIndex &index) const
{
    bool selected = (option.state & QStyle::State_Selected) == QStyle::State_Selected;

    if (selected)
    {
        painter->fillRect(option.rect, option.palette.highlight());
    }

    painter->save();
    painter->setRenderHint(QPainter::Antialiasing, true);

    if (selected)
    {
        painter->setPen(option.palette.highlightedText().color());
    }
    else
    {
        painter->setPen(option.palette.text().color());
    }

    mTextDocument.drawContents(painter);

    painter->restore();
}

QSize ProductItemDelegate::sizeHint(const QStyleOptionViewItem &option,
                              const QModelIndex &index) const
{
    MyItem *myItem = index.data(Qt::UserRole + 1).value<MyItem *>();

    mTextDocument->clear();
    mTextDocument->setDefaultFont(option.font);
    mTextDocument->setPageSize(QSizeF(option.rect.width(), -1));

    QTextCursor cursor = QTextCursor(mTextDocument);

    QVector<QTextLength> columnConstraints;
    columnConstraints << QTextLength(QTextLength::PercentageLength, 60);
    columnConstraints << QTextLength(QTextLength::PercentageLength, 30);
    columnConstraints << QTextLength(QTextLength::PercentageLength, 10);

    QTextTableFormat tableFormat;
    tableFormat.setBorder(1);
    tableFormat.setBorderBrush(QBrush(Qt::black));
    tableFormat.setColumnWidthConstraints(columnConstraints);

    QTextTable *table = cursor.insertTable(2, 3, tableFormat);
    table->mergeCells(0, 0, 1, 3);

    QTextCursor cellCursor;

    QTextTableCell cell00 = table->cellAt(0, 0);
    cellCursor = cell00.firstCursorPosition();
    cellCursor.insertText(myItem->name());

    QTextTableCell cell10 = table->cellAt(1, 0);
    cellCursor = cell10.firstCursorPosition();
    cellCursor.insertText(myItem->text1());

    QTextTableCell cell11 = table->cellAt(1, 1);
    cellCursor = cell11.firstCursorPosition();
    cellCursor.insertText(myItem->text2());

    return mTextDocument->size().toSize();
}

这些是上述代码的结果。

该项目未在第二个条目中绘制。 Capture 1

两个项目都在第一个条目中绘制。 Capture 2

1 个答案:

答案 0 :(得分:1)

在绘画之前,你应该把你的画家放在正确的位置。

第一次painter->save()添加后:

painter->resetTransform();
painter->translate(option.rect.topLeft());