Qt QTableView自定义列表(插入图片)

时间:2024-03-05 08:54:54

 

前几天写Qt,想实现一个列表功能去网上找了找,发现了使用QListWidget挺方便的,但总感觉不好看一种古老的气息;于是又在网上查了查发现可以用QTableView定制挺不错的;最后实现了结果发现表头还是不好看,不过好在有解决方法------自己重绘;接下来不多说上代码。

MyTableView.h

 class MyItemDelegate:public QItemDelegate
  {
  public:
      MyItemDelegate(QObject * parent=0);

      virtual ~ MyItemDelegate(){}
      void paint(QPainter * painter,
          const QStyleOptionViewItem & option,
          const QModelIndex & index) const;
     bool editorEvent(QEvent * event,
         QAbstractItemModel * model,
         const QStyleOptionViewItem & option,
         const QModelIndex & index);
 private:
     QPixmap favPixmap;
     QPixmap notfavPixmap;
 };

 class MyTableView : public QTableView {
     Q_OBJECT
 public:
     explicit MyTableView(QTableView *parent = 0);
     ~MyTableView();
     void InitView();
     void appendItem(int index, QString filename, QString date, QString filesize);
     void clear(){m_model->clear();}
 private:
     QStandardItemModel *m_model;
     QList<QString> m_listhead = {"0", QStringLiteral("文件名"), QStringLiteral("修改时间"), QStringLiteral("大小")};
 };
 #endif // MYTABLEVIEW_H

QItemDelegate,QTableView两个类重写继承QItemDelegate会在QTableView创建是使用到。

 

MyItemDelegate:

两个QPixmap 是点击时打勾和不打勾的图片

paint() 在这里重绘表头和QPixmap图片

editorEvent 响应鼠标点击列表的事件

 

MyTableView:

InitView() 初始化列表,一定要先执行。

appendItem() 增加一行列

clear() 清空

m_listhead 表头名称

 

MyTableView.cpp

  MyTableView::MyTableView(QTableView *parent) : QTableView(parent) {
      m_model = new QStandardItemModel(this);
  }
  
  MyTableView::~MyTableView() {
      delete m_model;
  }
 
 void MyTableView::InitView(int widindex) {
     QList<QStandardItem*> row;//设置列数
     m_model->setColumnCount(4);
     this->setIconSize(QSize(60, 60));
     this->setLayoutDirection(Qt::LeftToRight);
 
     //第一列空行
     m_model->appendRow(row);
 /*
     connect(this, SIGNAL(clicked(const QModelIndex &)), this, OT(RowClicked(const QModelIndex &)));
     connect(this, SIGNAL(doubleClicked(const QModelIndex &)), this, SLOT(RowDoubleClicked(const QModelIndex &)));
*/
 
     this->verticalHeader()->setDefaultSectionSize(60);
 
     this->setContextMenuPolicy(Qt::CustomContextMenu);
     this->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
     this->setFocusPolicy(Qt::NoFocus);
     this->horizontalHeader()->setHighlightSections(false);
     this->setEditTriggers(QAbstractItemView::NoEditTriggers);
     this->setShowGrid(false);
     this->setSelectionBehavior(QAbstractItemView::SelectRows);
     this->setSelectionMode(QAbstractItemView::SingleSelection);
     this->horizontalHeader()->resizeSections(QHeaderView::Interactive);
     this->verticalHeader()->hide();
     this->horizontalHeader()->hide();
 
 //    this->setAlternatingRowColors(true);
 //    this->setSortingEnabled(true);
     this->setItemDelegate(new MyItemDelegate());
     this->setModel(m_model);
 
     //设置行高和列宽
     //行高
     this->setRowHeight(0, 40);
     //列宽
     this->setColumnWidth(0, 60);
     this->setColumnWidth(1, 400);
     this->setColumnWidth(2, 140);
     this->setColumnWidth(3, 200);
 //    this->setColumnWidth(4, 60);
 
     this->setFocus();
 }
 
 void MyTableView::appendItem(int index, QString filename, QString date, QString filesize) {
     QList<QStandardItem*> row;
  //自定义图片 根据自己的修改
     QIcon icon[5] = {
         QIcon(":/first/res/image/dir.png"),         
         QIcon(":/first/res/image/pic.png"),
         QIcon(":/first/res/image/txt.png"),
         QIcon(":/first/res/image/zip.png"),
         QIcon(":/first/res/image/unkown.png"),
                     };
     if(index == 0) row.push_back(new QStandardItem("*"));
     else row.push_back(new QStandardItem(""));
     row.push_back(new QStandardItem(icon[index], filename));
     row.push_back(new QStandardItem(date));
     row.push_back(new QStandardItem(filesize));
 //    row.push_back(new QStandardItem(0));
     m_model->appendRow(row);
 }
 
 MyItemDelegate::MyItemDelegate(QObject * parent)
 :QItemDelegate(parent)
 {
     favPixmap=QPixmap(":/first/res/image/select.png");
     nofavPixmap=QPixmap(":/first/res/image/unsel.png");
 }
 
 void MyItemDelegate::paint(QPainter * painter,
                            const QStyleOptionViewItem & option,
                            const QModelIndex & index) const
 {
     if(index.column()!=0) {
         if(index.row() == 0) {
             painter->setFont(QFont("Microsoft Yahei", 9, -1, false));
             painter->drawText(option.rect.x()+10, option.rect.y()+20, m_listhead.at(index.column()));
             return;
         }
         QItemDelegate::paint(painter,option,index);
         return;
    }
 
     const QAbstractItemModel * model=index.model();
 
     QVariant var=model->data(index,Qt::CheckStateRole);
     if(var.isNull()) var=false;
 //    qDebug() << var.toBool();
 
     const QPixmap star = var.toBool()?favPixmap:notfavPixmap;

     int width=p=star.width();
     int height=star.height();
     QRect rect=option.rect;
     int x=rect.x()+rect.width()/2-width/2;
     int y=rect.y()+rect.height()/2-height/2;

     painter->drawPixmap(x,y, star);
 }
 
 bool MyItemDelegate::editorEvent(QEvent * event,
                                  QAbstractItemModel * model,
                                  const QStyleOptionViewItem &, //option
                                  const QModelIndex & index)
 {
     if(event->type()==QEvent::MouseButtonDblClick) {
 
     }
     if(event->type()==QEvent::MouseButtonPress) {
     if(index.column() == 0) {
      QVariant var=m_model->data(index,
                                              Qt::ItemDataRole::CheckStateRole);
                 bool isFavourite=var.toBool();
                 if(var.isValid())
                     isFavourite=isFavourite?false:true;
                 else
                     isFavourite=true;
                 m_model->setData(index,isFavourite,Qt::CheckStateRole);

      }
     }
     //false Is To Later Process
     return false;
 }

 

效果图:

 

重绘的好处在于点击不会有黑色的阴影,不过要加一行无用行来被用来表头覆盖

关键的地方我已经标好了注释 大家可以自行修改代码来实现不同功能

有问题或有错误欢迎大家Call我。。。。。。