Qt的tableview实现按键委托的问题:
1、使用一般的方法,即只是用createEditor、setEditorData、setModelData、updateEditorGeometry
这几个函数实现的话,每次必须双击单元格,才会显示出按键;
2、绘制的按钮大小不会随着单元格的变化而变化;
为了解决这两个问题使用paint函数和editorEvent函数替换createEditor函数画出按键,问题解决。代码如下:
bool BDelegate::editorEvent(QEvent *event, QAbstractItemModel *model, const QStyleOptionViewItem &option, const QModelIndex &index)
{
if((1 == index.column()) && (14 != model->data(model->index(index.row(),0)))){
if (event->type() == QEvent::MouseButtonPress) {
QMouseEvent* e =(QMouseEvent*)event;
if (option.rect.adjusted(4, 4, -4, -4).contains(e->x(), e->y()) && m_btns.contains(index)) {
m_btns.value(index)->state |= QStyle::State_Sunken;
}
}
if (event->type() == QEvent::MouseButtonRelease) {
QMouseEvent* e =(QMouseEvent*)event;
if (option.rect.adjusted(4, 4, -4, -4).contains(e->x(), e->y()) && m_btns.contains(index)) {
m_btns.value(index)->state &= (~QStyle::State_Sunken);
qDebug() << model->data(model->index(index.row(),0));
ConItem01 *d = new ConItem01(); //弹窗提示
d->setGeometry(0, 0, 800, 400);
d->move(QApplication::desktop()->screenGeometry().center() - d->rect().center());
</pre><pre name="code" class="cpp"><span style="white-space:pre"> </span>d->exec();
delete d;
}
return true;
}
return false;
}
void BDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
if(0 == index.column()){ //这个放第一行会出现显示多出一个标号,除非使用else if结构
QStyleOptionViewItemV4 myOption = option;
int x = index.model()->data(index, Qt::EditRole).toUInt();
QString text = Items.at(x);
myOption.text = text;
QApplication::style()->drawControl(QStyle::CE_ItemViewItem, &myOption, painter);
}else if(1 == index.column() && (14 != index.model()->data(index.model()->index(index.row(),0)))){
QStyleOptionButton* button = m_btns.value(index);
if (!button) {
button = new QStyleOptionButton();
//button->rect = option.rect.adjusted(4, 4, -4, -4);//放这里,固定大小
button->text = "设置参数";
button->state |= QStyle::State_Enabled;
(const_cast<BDelegate *>(this))->m_btns.insert(index, button);
}
button->rect = option.rect.adjusted(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, button, painter);
}else {
return QItemDelegate::paint (painter, option, index);
}
}