Qt之QComboBox(委托)

   QQ中有多账号管理的操作,易用性很好,之前实现过,可参考: Qt之QComboBox(基本应用、代理设置) ,下面介绍另外一种方式,使用委托来实现!

   Qt之QComboBox(委托)_第1张图片

代码如下:
#ifndef ITEMDELEGATE_H #define ITEMDELEGATE_H #include class ItemDelegate : public QStyledItemDelegate { Q_OBJECT signals: void deleteItem(const QModelIndex &index); public: ItemDelegate(QObject * parent=0); ~ItemDelegate(){} void paint(QPainter * painter,const QStyleOptionViewItem & option,const QModelIndex & index) const; bool editorEvent(QEvent *event, QAbstractItemModel *model, const QStyleOptionViewItem &option, const QModelIndex &index); }; #endif // ITEMDELEGATE_H
#include "ItemDelegate.h" #include #include #include #include #include ItemDelegate::ItemDelegate(QObject * parent) : QStyledItemDelegate(parent) { } void ItemDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const { QStyleOptionViewItem viewOption(option); if (viewOption.state & QStyle::State_HasFocus) { viewOption.state = viewOption.state ^ QStyle::State_HasFocus; } QStyledItemDelegate::paint(painter, viewOption, index); int height = (viewOption.rect.height() - 9) / 2; QPixmap pixmap = QPixmap(":/delete"); QRect decorationRect = QRect(viewOption.rect.left() + viewOption.rect.width() - 30, viewOption.rect.top() + height, 9, 9); painter->drawPixmap(decorationRect, pixmap); } bool ItemDelegate::editorEvent(QEvent *event, QAbstractItemModel *model, const QStyleOptionViewItem &option, const QModelIndex &index) { int height = (option.rect.height() - 9) / 2; QRect decorationRect = QRect(option.rect.left() + option.rect.width() - 30, option.rect.top() + height, 9, 9); QMouseEvent *mouseEvent = static_cast(event); if (event->type() == QEvent::MouseButtonPress && decorationRect.contains(mouseEvent->pos())) { emit deleteItem(index); } if (event->type() == QEvent::MouseMove && decorationRect.contains(mouseEvent->pos())) { QCursor cursor(Qt::PointingHandCursor); QApplication::setOverrideCursor(cursor); QString strText = QStringLiteral("删除账号信息"); QToolTip::showText(mouseEvent->globalPos(), strText); } else { QCursor cursor(Qt::ArrowCursor); QApplication::setOverrideCursor(cursor); } return QStyledItemDelegate::editorEvent(event, model, option, index); }
ItemDelegate *pDelegate = new ItemDelegate(this); ui->comboBox->setItemDelegate(pDelegate); connect(pDelegate, SIGNAL(deleteItem(QModelIndex)), this, SLOT(deleteItem(QModelIndex))); void Widget::deleteItem(const QModelIndex &index) { if (QMessageBox::question(this, QStringLiteral("提示"), QStringLiteral("确认要删除所选账号吗?"), QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes) == QMessageBox::Yes) { ui->comboBox->removeItem(index.row()); } }
效果如下:

Qt之QComboBox(委托)_第2张图片

Qt之QComboBox(委托)_第3张图片

    源码地址: http://download.csdn.net/detail/u011012932/8467085。

注:
    技术在于交流、沟通,转载请注明出处并保持作品的完整性。
     作者: ╰☆奋斗ing❤孩子`   原文: http://blog.sina.com.cn/s/blog_a6fb6cc90102vces.html。

你可能感兴趣的:(Qt之QComboBox(委托))