实现功能:
Model/View框架中的Delgate负责单元格的显示。自己定义如何编辑列表listwidget中的项item。
1、定义每一项的显示大小。
2、显示其data:显示姓名、电话号码,插入表示性别data的图像。
代码实现:
1、派生一个QStyledItemDelegate的类对象MyItemDrawer。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| #ifndef MYITEMDRAWER_H #define MYITEMDRAWER_H #include <QStyledItemDelegate> #include <QIcon>
class MyItemDrawer : public QStyledItemDelegate { public: MyItemDrawer(QWidget *parent); private: virtual void paint(QPainter *painter,const QStyleOptionViewItem &option,const QModelIndex &index)const; virtual QSize sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const; private: QPixmap m_male; QPixmap m_female;
};
#endif 123456789101112131415161718192021
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
| #include "myitemdrawer.h" #include <QPainter>
MyItemDrawer::MyItemDrawer(QWidget *parent) { m_male.load("C:/Users/Maggie/Downloads/male.png"); m_female.load("C:/Users/Maggie/Downloads/female.png");
} QSize MyItemDrawer::sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const { QSize size=QStyledItemDelegate::sizeHint(option,index); size.setHeight(80); return size; } void MyItemDrawer::paint(QPainter* painter,const QStyleOptionViewItem &option,const QModelIndex &index)const { QRect rect=option.rect; rect.adjust(2,2,-2,-2); QString name=index.data(Qt::DisplayRole).toString(); QString phone=index.data(Qt::UserRole+1).toString(); bool gender=index.data(Qt::UserRole+1).toBool();
if(option.state&QStyle::State_Selected) { painter->setBrush(QColor(0xCC,0xAA,0xaa)); painter->drawRoundedRect(rect,2,2); painter->setBrush(Qt::NoBrush); } if(1) { QRect dst=rect; dst.setLeft(rect.left()+40); dst.setBottom(rect.top()+20); painter->drawText(dst,Qt::AlignLeft|Qt::AlignVCenter,name); } if(1) { QRect dst = rect; dst.setLeft(rect.left() + 40); dst.setTop(rect.top() + 20); painter->drawText(dst, Qt::AlignLeft | Qt::AlignVCenter,phone); } if(1) { QRect dst=rect; dst.setRight(rect.left()+40); QRect area(0,0,24,24); area.moveCenter(dst.center()); painter->drawPixmap(area,gender?m_male:m_female); } }
|
2、MainWindow主窗口类中实现AddItem函数:
1 2 3 4 5 6 7 8
| void MainWindow::AddItem(QString name,QString phone,bool gender) { QListWidgetItem *item=new QListWidgetItem(); item->setData(Qt::DisplayRole,name); item->setData(Qt::UserRole+1,phone); item->setData(Qt::UserRole+2,gender); ui->listWidget->addItem(item); }12345678
|
3、在MainWindow类构造函数中:
1 2 3 4 5
| AddItem("zzn","13922233333",false); AddItem("hw","13833322222",true);
ui->listWidget->setItemDelegate(new MyItemDrawer(ui->listWidget));
|