Men的博客

欢迎光临!

0%

QT实战表单绘制多个按钮

这个确实难倒我了,我百度了很多地方最终也不甚明白,特别是在绘制的地方,当我调整绘制样式的时候真是的费了九牛二虎之力啊,太难了,下面展示下代码吧

void PosInfoTableDelegate::paint(QPainter painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
QPair<QStyleOptionButton*, 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 = QStringLiteral(“查看”);
QPalette pal = button1->palette; // 这里是为了让文本颜色的修改,这个调色板还有很多接口,但是我操作很多都无法改变背景色,让我很失望
pal.setColor(QPalette::ButtonText, QColor(255, 255, 255));
button1->palette = pal;
button1->icon = QIcon(“://largeImage.png”);
button1->iconSize = QSize(40,40);

    QStyleOptionButton* button2 = new QStyleOptionButton();
    button2->rect = option.rect.adjusted(button1->rect.width() + 4, 4, -4, -4);
    button2->icon =  QIcon("://closeTab.png");
    button2->iconSize = QSize(40,40);
    buttons =new  QPair<QStyleOptionButton*, QStyleOptionButton*>(button1, button2);
    (const_cast<PosInfoTableDelegate *>(this))->m_btns.insert(index, buttons);
}
buttons->first->rect = option.rect.adjusted(4, 4, -(option.rect.width() / 2 + 4) , -4); //
buttons->second->rect = option.rect.adjusted(buttons->first->rect.width() + 4, 4, -4, -4);
painter->save();

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

}
painter->restore();
// 这个地方CE_PushButtonLabel 是为了防止按钮带背景色,我曾采用n种方式都无法去除背景色,最后只能这样了
QApplication::style()->drawControl(QStyle::CE_PushButtonLabel, buttons->first, painter);
QApplication::style()->drawControl(QStyle::CE_PushButtonLabel, buttons->second, painter);

}
// 这个是点击事件,不多说
bool PosInfoTableDelegate::editorEvent(QEvent event, QAbstractItemModel model, const QStyleOptionViewItem &option, const QModelIndex &index)
{
if (event->type() == QEvent::MouseButtonRelease) {
QMouseEvent
e =(QMouseEvent
)event;
if (m_btns.contains(index)) {
QPair<QStyleOptionButton*, QStyleOptionButton*>* btns = m_btns.value(index);
if (btns->first->rect.contains(e->x(), e->y())) {
emit lookRow(index.row());
} else if(btns->second->rect.contains(e->x(), e->y())) {
btns->second->state &= (~QStyle::State_Sunken);
emit deleteRow(index.row());
}
}
}
return false;
}