Qt之QComboBox(委託)

   QQ中有多帳號管理的操做,易用性很好,以前實現過,可參考: Qt之QComboBox(基本應用、代理設置) ,下面介紹另一種方式,使用委託來實現!

   Qt之QComboBox(委託)

代碼以下:
#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(委託)

Qt之QComboBox(委託)


注:
    技術在於交流、溝通,轉載請註明出處並保持做品的完整性。
相關文章
相關標籤/搜索