我打算在表格的某列里实现多个按键,用的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;