T
T
tschin2016-12-20 16:54:22
Qt
tschin, 2016-12-20 16:54:22

How to override the paint() method in a delegate?

Hello! There is a QTableWidget. Some columns and rows have delegates. In delegates, data changes dynamically. To display the change in this data, in addition to adding them to the delegate, you also have to loop through the table cells and change the QTableWidgetItem. It would be desirable not to go on cells in a cycle. In order for the data to be immediately displayed after being added to the delegate, as I understand it, you need to override the virtual paint() method . I can't figure out how to do it at all.
I used this article as an example .
Here's what I got:

void ComboBoxDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    QString itemText = index.data().toString();
    QStyleOptionViewItem viewItem;
    QRect r = option.rect;
    r.setHeight( option.rect.height() );
    r.moveCenter( option.rect.center() );
    viewItem.rect = r;
    viewItem.displayAlignment = Qt::AlignCenter;
    viewItem.text= itemText;
    QItemDelegate::paint( painter, option, QModelIndex() );
}

Crashes with warnings:
ASSERT: "index.isValid()" in file itemviews\qitemdelegate.cpp, line 392
QWidget::repaint: Recursive repaint detected
ASSERT: "index.isValid()" in file itemviews\qitemdelegate.cpp, line 392
D:\Qt_project\new-conf\new_conf\debug\new_conf.exe exited with code 3

Answer the question

In order to leave comments, you need to log in

1 answer(s)
T
tschin, 2016-12-22
@tschin

Here's an option that works as it should:

void ComboBoxDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    QString itemText = index.data().toString();

    QStyleOptionViewItem optionViewItem;
    optionViewItem.text = itemText;
    optionViewItem.rect = option.rect;

    QApplication::style()->drawItemText(painter,
                                        optionViewItem.rect,
                                        Qt::AlignCenter,
                                        QApplication::palette(),
                                        true,
                                        optionViewItem.text);
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question