QTableView的表格项中加入图标的方法(重载View::mouseMoveEvent,并使用View::setIconSize函数设置图标的大小)

当在使用表格视图的时候,需要在表格每一行前面加入图标,应该怎么做呢?Qt中通过使用MVC的处理方式,很容易做到这一点,具体实现如下:

先贴出图,让大家一睹为快

下面我就来介绍一下,上图的灯泡是怎么实现的,通过重载QAbstractTableModel中的data方法,如下:(CTblModel 派生自QAbstractTableModel)

[cpp] view plain copy
 
 在CODE上查看代码片派生到我的代码片
  1. QVariant CTblModel::data(const QModelIndex &index, int role) const  
  2. {  
  3.     if (!index.isValid())  
  4.         return QVariant();  
  5.       
  6.     int col = index.column();  
  7.     if (col == ledColIndex && role == Qt::DecorationRole)  
  8.     {  
  9.         return QIcon(":/images/light.png");  
  10.     }  
  11.     else  
  12.     {  
  13.         ...  
  14.     }  
  15.     return QVariant();  
  16. }  

对于mvc的使用方法,请参考http://blog.csdn.net/rabinsong/article/details/8452946

让图片动起来,能够响应用户事件,当用户单击灯泡时,灯泡会点亮,这个怎么实现呢?

要实现这个功能,首先要能接受到鼠标事件,其次,要知道鼠标点击了灯泡部分,不能鼠标不在灯泡上点击,灯泡也亮。有了这两点,下面我们来看看实现:

我们可以通过重载QTableView的 mousePressEvent(),从而获得对鼠标单击的控制权,通过indexAt方找到当前单击的index,再根据索引找到灯泡所在的列,具体实现如下:

[cpp] view plain copy
 
 在CODE上查看代码片派生到我的代码片
  1. void CTblView::mouseMoveEvent(QMouseEvent *event)  
  2. {  
  3.     const QPoint &p = event->pos();  
  4.     QModelIndex modelIndex = indexAt(p);  
  5.     if (modelIndex.isValid())  
  6.     {  
  7.         int col = modelIndex.column();  
  8.         int row = modelIndex.row();  
  9.         if (col == ledColIndex)  
  10.         {  
  11.             pTblModel->setLight(row);  
  12.         }  
  13.     }  
  14. }  


pTblModel就是上面定义的CTblModel,到了这里大家应该知道了基本实现思路了吧。

让图标变大一些,按照上面的做法,灯泡图标的大小很小,不管你的light.png图片多大,在表格中显示时的图标大小默认都很小,那么怎么改变图标的大小呢?方法也很简单,就是在CTblView构造函数中加入setIconSize(QSize(25,25));我设置的是25*25大小,显示效果如上图的灯泡效果,大家可以根据自己的应用,调整其大小。

http://blog.csdn.net/rabinsong/article/details/13158281

原文地址:https://www.cnblogs.com/findumars/p/5615721.html