hydelios
2021-05-12 11:07
采纳率: 33.3%
浏览 26

qt QtItemDelegate实现paint遇到问题

我打算在表格的某列里实现多个按键,用的QtItemDelegate实现paint,我使用了QVector,但不知道为什么在向button里push_back的时候程序会崩溃


void ButtonDelegateAC::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    QVector<QStyleOptionButton*>* buttons = m_btns.value(index);

    if (!buttons) {
        QStyleOptionButton* button1 = new QStyleOptionButton();
        //button1->rect = option.rect.adjusted(4, 4, -(option.rect.width() / 2 + 4) , -4); //
        button1->text = "编辑账户";
        button1->state |= QStyle::State_Enabled;
        buttons->push_back(button1);

        QStyleOptionButton* button2 = new QStyleOptionButton();
        //button2->rect = option.rect.adjusted(button1->rect.width() + 4, 4, -4, -4);
        button2->text = "注销账户";
        button2->state |= QStyle::State_Enabled;
        buttons->push_back(button2);

        QStyleOptionButton* button3 = new QStyleOptionButton();
        //button2->rect = option.rect.adjusted(button1->rect.width() + 4, 4, -4, -4);
        button3->text = "注销账户";
        button3->state |= QStyle::State_Enabled;
        buttons->push_back(button3);

        QStyleOptionButton* button4 = new QStyleOptionButton();
        //button2->rect = option.rect.adjusted(button1->rect.width() + 4, 4, -4, -4);
        button4->text = "注销账户";
        button4->state |= QStyle::State_Enabled;
        buttons->push_back(button4);
        (const_cast<ButtonDelegateAC *>(this))->m_btns.insert(index, buttons);
    }
    (*buttons)[0]->rect = option.rect.adjusted(4, 4, -(option.rect.width() / 2 + 4) , -4); //
    (*buttons)[1]->rect = option.rect.adjusted((*buttons)[0]->rect.width() + 4, 4, -4, -4);
    (*buttons)[2]->rect = option.rect.adjusted((*buttons)[1]->rect.width() + 4, 4, -4, -4); //
    (*buttons)[3]->rect = option.rect.adjusted((*buttons)[2]->rect.width() + 4, 4, -4, -4);
    painter->save();

    if (option.state & QStyle::State_Selected) {
        painter->fillRect(option.rect, option.palette.highlight());

    }
    painter->restore();
    QApplication::style()->drawControl(QStyle::CE_PushButton, (*buttons)[0], painter);
    QApplication::style()->drawControl(QStyle::CE_PushButton, (*buttons)[1], painter);
    QApplication::style()->drawControl(QStyle::CE_PushButton, (*buttons)[2], painter);
    QApplication::style()->drawControl(QStyle::CE_PushButton, (*buttons)[3], painter);
}

其中m_btns是一个map

m_btns.value(index);

定义如下

typedef QMap<QModelIndex, QVector<QStyleOptionButton*>* >  collButtons;
    collButtons m_btns;
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • qfl_sdu 2021-05-12 12:04
    已采纳

    buttons 可能是空指针,跟一下看看吧,如有帮助,请采纳一下,谢谢。

    打赏 评论
  • cy1_cy2006 2021-05-12 11:38

    buttons是空指针,值是nullptr啊

    打赏 评论

相关推荐 更多相似问题