Qt之mvc模式——QHeadView详解已经应用

14 篇文章 0 订阅

QHeaderView类为项目视图提供标题行或标题列。

QHeaderView显示项目视图(如QTableView和QTreeView类)中使用的标题。它取代了Qt3的QHeader类,QHeader类以前用于相同的目的,但是为了与item视图类保持一致,它使用了Qt的模型/视图体系结构。

QHeaderView类是模型/视图类之一,是Qt模型/视图框架的一部分。

header使用qAbstracteModel::headerData()函数从模型中获取每个节的数据。可以使用qAbstracteModel::setHeaderData()设置数据。所以我们必须要重写qAbstracteModel

每个头都有一个orientation()和一个由count()函数给定的部分。节是指标题的一部分-行或列,具体取决于方向。

可以使用moveSection()和resizeSection()移动节并调整其大小;也可以使用hideSection()和showSection()隐藏和显示节。

头部的每个部分都由其section()指定的部分ID描述,并且可以位于头部中的特定visualIndex()处。节可以使用setSortIndicator()设置排序指示符;这表示是否按节给定的顺序对关联项视图中的项进行排序。

对于水平标题,节相当于模型中的列,对于垂直标题,节相当于模型中的行。

 

这里我继承重写了QHeadView ,封装了自己HeadView为了方便设置属性和管理

#include <QObject>
#include <QHeaderView>
#include <QUrl>
#include <QPainter>
#include <QMouseEvent>
#include <QApplication>
#include "htcore/Core.h"

class HCommonHeaderView : public QHeaderView
{
    Q_OBJECT
    Q_PROPERTY(int textAlign READ getTextAlign WRITE setTextAlign )  //!表头文本对齐方式
    Q_PROPERTY(QColor bgColor MEMBER m_gbColor)                      //!section背景颜色
    Q_PROPERTY(QColor borderColor MEMBER m_borderColor )             //!边框颜色*/
    Q_PROPERTY(int leftMargin MEMBER m_iLeftMargin )                 //!section做边距
    Q_PROPERTY(QUrl ascendingOrderUrl MEMBER  m_ascendingOrderUrl)   //!递增图标
    Q_PROPERTY(QUrl descendingOrderUrl MEMBER  m_descendingOrderUrl) //!递减图标
public:
    explicit HCommonHeaderView(Qt::Orientation orientation = Qt::Horizontal,QWidget *parent = 0);

    void restoreDefaultState();

    void setHeaderText(const QStringList &list);
    void setHeaderText_NoSort(const QStringList &list);
    void setCurSortColumn(int column);
    int getCurSortIndex() const;

    void setTextAlign(int flag);       //设置表头列文字位置
    int getTextAlign() const;          //获取表头列文字位置
    QUrl getAscendingOrderUrl() const; //获取递增图标url
    QUrl getDescendingOrderUrl() const;//获取递减图标url

    ///
    /// \brief setCheckBoxForColumn
    /// \param column
    ///  设置检查框对应的列,不设置则没有检查框
    ///
    void setCheckBoxForColumn(int column);

    ///
    /// \brief getCheckState
    /// \return
    ///  得到当前检查框状态
    ///
    Qt::CheckState getCheckState() const;

    //!
    //!设置整全部行数的对齐方式
    //! flag:true(设置全部列数);flase:(设置model数据的对齐方式)
    void setAllColumnAligFlag(bool flag);
    bool getBSortFlag() const;
    void setBSortFlag(bool value);

    void setShowBottonLine(bool value);

signals:
    //!
    //! \brief check状态改变
    //!
    void signalCheckStateChanged(Qt::CheckState);
    //!
    //! \brief signalSortStateChanged 排序信号
    //! \param logicalIndex           列序号
    //!
    void signalSortStateChanged(int logicalIndex);

public slots:
    //!
    //! \brief slotCheckStateChanged  改变check状态
    //! \param state  check状态
    //!
    void slotCheckStateChanged(Qt::CheckState state);

protected:
    ///
    /// \brief paintSection
    /// \param painter
    /// \param rect
    /// \param logicalIndex
    ///  绘制表头
    ///
    void paintSection(QPainter *painter, const QRect &rect, int logicalIndex) const;

    ///
    /// \brief mousePressEvent
    /// \param e
    /// 模拟鼠标点击
    ///
    void mousePressEvent(QMouseEvent *e);

    ///
    /// \brief mouseReleaseEvent
    /// \param e
    ///  检查鼠标释放位置是否合理,合理则处理鼠标点击,反之,不处理。
    ///
    void mouseReleaseEvent(QMouseEvent *e);

private:
    void setCheckState(Qt::CheckState state);

    ///
    /// \brief paintSortIndicatorIcon
    /// \param painter
    /// \param rect
    /// 绘制排序图标
    ///
    void paintSortIndicatorIcon(QPainter *painter, const QRect &rect, int logicIndex) const;

    ///
    /// \brief paintCheckBoxIcon
    /// \param painter
    /// \param rect
    /// 绘制组合框图标
    ///
    void paintCheckBoxIcon(QPainter *painter, const QRect &rect) const;

    ///
    /// \brief paintSectionRightBorderLine
    /// \param painter
    /// \param rect
    /// 绘制表头section右边界线
    ///
    void paintSectionRightBorderLine(QPainter *painter, const QRect &rect) const;

    void paintSectionText(QPainter *painter, const QRect &rect, int logicIndex) const;



private:
    QVector<int> m_sortColumnLst;  //存储能够进行排序的索引
    QStringList m_headerLst;

    Qt::CheckState m_checkBoxState;
    int m_iSortIndex;

    bool m_bMousePressed;
    bool m_bSectionSizeChanging;
    int m_bPressedIndex;

    int m_iTextAlign;   //文本对齐方式
    int m_iLeftMargin;  //左边距
    QColor m_gbColor;  //背景色
    QColor m_borderColor; //边框颜色
    int m_iCheckBoxColumn; //表头列,对应的检查框
    bool m_bIsFirst;
    QUrl m_ascendingOrderUrl;
    QUrl m_descendingOrderUrl;
    bool bAllColumnAlgFlag{true}; //设置全部行列的对齐方式标志
    bool bSortFlag;
    bool mbShowBottonLine{false};

};

 

下面是源文件的实现

#include "HCommonHeaderView.h"
#include <QRgba64>
#define ICON_SIZE 12          //图标大小
#define ICON_RIGHT_MARGIN 6   //离右边缘间距
#define HEADER_HEIGHT 18      //表头高


HCommonHeaderView::HCommonHeaderView(Qt::Orientation orientation, QWidget *parent)
    : QHeaderView(orientation,parent)
    ,m_checkBoxState(Qt::Unchecked)
    ,m_bMousePressed(false)
    ,m_bSectionSizeChanging(false)
    ,m_iCheckBoxColumn(999)
    ,m_bPressedIndex(999)
    ,m_iSortIndex(999)
    ,m_bIsFirst(true)
    ,bSortFlag(true)
{
    this->setSortIndicatorShown(false);
    setTextAlign(0);
    m_gbColor = QColor("#282D35");
    this->setSectionResizeMode(QHeaderView::Interactive);

    for(int i = 0; i < 20; ++i)
    {
        m_headerLst.append("");
    }
    connect(this,&HCommonHeaderView::sectionResized,[&](){ // 列拖动改变大小
        m_bSectionSizeChanging = true;
    });
}

void HCommonHeaderView::restoreDefaultState()
{
    m_checkBoxState = Qt::Unchecked;
    this->viewport()->update();
}

void HCommonHeaderView::setHeaderText(const QStringList &list)
{
    m_headerLst.clear();
    m_headerLst = list;
    for(int i = 0; i < list.count() - 1; i++)
    {
        m_sortColumnLst.append(i);
    }
}

void HCommonHeaderView::setCurSortColumn(int column)
{
    m_iSortIndex = column;
    this->viewport()->update();
}

int HCommonHeaderView::getCurSortIndex() const
{
    return m_iSortIndex;
}

void HCommonHeaderView::setTextAlign(int flag)
{
    m_iTextAlign = flag;
}

int HCommonHeaderView::getTextAlign() const
{
    return m_iTextAlign;
}

QUrl HCommonHeaderView::getAscendingOrderUrl() const
{
    return m_ascendingOrderUrl;
}

QUrl HCommonHeaderView::getDescendingOrderUrl() const
{
    return m_descendingOrderUrl;
}

void HCommonHeaderView::setCheckBoxForColumn(int column)
{
    m_iCheckBoxColumn = column;
}

void HCommonHeaderView::slotCheckStateChanged(Qt::CheckState state)
{
    if(state != m_checkBoxState) {
        m_checkBoxState = state;
        this->viewport()->update();
    }
}

void HCommonHeaderView::paintSection(QPainter *painter, const QRect &rect, int logicalIndex) const
{
    painter->save();
    QHeaderView::paintSection(painter, rect, logicalIndex);
    painter->restore();
    QPen pen(QColor(200,200,200,255));
    painter->setPen(pen);
    QFont font = painter->font();
    font.setPixelSize(12);
    painter->setFont(font);
    paintSectionText(painter,rect,logicalIndex);

    if(logicalIndex == m_iCheckBoxColumn)
    {
        paintCheckBoxIcon(painter,rect);
    }
    else if( m_iSortIndex == logicalIndex && bSortFlag)
    {
        paintSortIndicatorIcon(painter,rect,logicalIndex);
    }
    if(logicalIndex == m_iCheckBoxColumn)
    {
        return;
    }
    if(logicalIndex == m_headerLst.count() - 1) return;
    paintSectionRightBorderLine(painter,rect);
}

void HCommonHeaderView::mousePressEvent(QMouseEvent *e)
{
    int column = logicalIndexAt(e->pos());
    if(column >= 0 ) {
        m_bMousePressed = true;
        m_bPressedIndex = column;
    }
    QHeaderView::mousePressEvent(e);
}

void HCommonHeaderView::mouseReleaseEvent(QMouseEvent *e)
{
    int column = logicalIndexAt(e->pos());
    //    if(m_bIsFirst) {
    //        m_bSectionSizeChanging = false;
    //        m_bIsFirst = false;
    //    }
    if( column >= 0 && !m_bSectionSizeChanging)
    {
        if(column == m_iCheckBoxColumn && m_bPressedIndex == column) //检查框被点击
        {
            this->setCheckState( (m_checkBoxState == Qt::Checked) ? Qt::Unchecked : Qt::Checked );
        }
        else if(column != m_iCheckBoxColumn)
        {
            m_iSortIndex = column;
            emit signalSortStateChanged(m_iSortIndex);
        }
        this->viewport()->update();
    }
    m_bMousePressed = false;
    m_bSectionSizeChanging = false;
    QHeaderView::mouseReleaseEvent(e);
}

void HCommonHeaderView::setCheckState(Qt::CheckState state)
{
    m_checkBoxState = state;
    emit signalCheckStateChanged(state);
}

Qt::CheckState HCommonHeaderView::getCheckState() const
{
    return m_checkBoxState;
}

void HCommonHeaderView::paintSortIndicatorIcon(QPainter *painter, const QRect &rect,int logicIndex) const
{
    if(m_headerLst.at(logicIndex) == "" && !m_sortColumnLst.contains(logicIndex) )
    {
        return;
    }
    int y1 = rect.y() + (rect.height() - HEADER_HEIGHT) / 2;

    QRect tmpRect ;
    tmpRect.setY(y1);
    tmpRect.setX(rect.x());
    tmpRect.setHeight(HEADER_HEIGHT);
    tmpRect.setWidth(rect.width());

    if(m_iTextAlign == 1)
    {
        tmpRect = tmpRect.adjusted(m_iLeftMargin,0,m_iLeftMargin,0);
    }

    QFontMetrics metrics = painter->fontMetrics();
    QRect textRect = metrics.boundingRect(tmpRect,m_iTextAlign|Qt::AlignVCenter,m_headerLst.at(logicIndex));

    QUrl iconUrl  =m_descendingOrderUrl;
    if(this->sortIndicatorOrder() == Qt::AscendingOrder)
    {
        iconUrl  = m_ascendingOrderUrl;
    }

    QPixmap tmp(QString("HTSkin:%1/%2").arg(HCore::instance()->getCurrentSkinId())
                .arg(iconUrl.path()));

    QRect iconRect = textRect.adjusted(ICON_RIGHT_MARGIN + textRect.width(),0,ICON_RIGHT_MARGIN + textRect.width(),0);
    QApplication::style()->drawItemPixmap(painter,iconRect,Qt::AlignLeft|Qt::AlignVCenter,tmp);
}

void HCommonHeaderView::paintCheckBoxIcon(QPainter *painter, const QRect &rect) const
{
    Q_UNUSED(painter);
    Q_UNUSED(rect);
    //    QUrl iconUrl;
    //    switch(m_checkBoxState) {
    //        case Qt::Unchecked: {
    //            iconUrl = BD_GL_ALGORITHMIC_COMMON_STYLE->getUncheckUrl();
    //        } break;
    //        case Qt::PartiallyChecked: {
    //            iconUrl = BD_GL_ALGORITHMIC_COMMON_STYLE->getPartCheckUrl();
    //        } break;
    //        case Qt::Checked: {
    //            iconUrl = BD_GL_ALGORITHMIC_COMMON_STYLE->getCheckUrl();
    //        } break;
    //    }
    //    QPixmap tmp(QString("BDSkin:%1/%2").arg(gBDCore->getCurrentSkinId())
    //                .arg(iconUrl.path()));

    //    QApplication::style()->drawItemPixmap(painter,rect.adjusted(0,0,-6,0),Qt::AlignVCenter|Qt::AlignRight,tmp);
}

void HCommonHeaderView::paintSectionRightBorderLine(QPainter *painter, const QRect &rect) const
{
    int x1 = rect.right();
    int y1 = rect.y() + (rect.height() - HEADER_HEIGHT) / 2;

    int x2 = x1;
    int y2 = y1 + HEADER_HEIGHT;

    //! [0]
    painter->save();
    //! [1]
    QPen pen;
    pen.setColor(m_borderColor);
    pen.setWidth(2);
    painter->setPen(pen);
    //! [2]
    painter->setRenderHint(QPainter::Antialiasing);
    painter->drawLine(QPoint(x1,y1),QPoint(x2,y2));

    if(mbShowBottonLine){
        painter->drawLine(QPoint(rect.left(),rect.height()),QPoint(rect.right(),rect.height()));
    }
    //! [3]
    painter->restore();
}

void HCommonHeaderView::paintSectionText(QPainter *painter, const QRect &rect, int logicIndex) const
{
    int y1 = rect.y() + (rect.height() - HEADER_HEIGHT) / 2 -3;

    QRect tmpRect ;
    tmpRect.setY(y1);
    tmpRect.setX(rect.x());
    tmpRect.setHeight(HEADER_HEIGHT);
    tmpRect.setWidth(rect.width());


    painter->fillRect(rect,m_gbColor);
    if( m_iCheckBoxColumn == logicIndex ) return;
    painter->save();
    if(bAllColumnAlgFlag ){
        if(m_iTextAlign == 1) {//左对齐
            painter->drawText(tmpRect.adjusted(m_iLeftMargin,0,m_iLeftMargin,0),m_iTextAlign|Qt::AlignVCenter,m_headerLst.at(logicIndex));
        }else{
            painter->drawText(tmpRect,m_iTextAlign|Qt::AlignVCenter,m_headerLst.at(logicIndex));
        }
    }else{  //这个是根据model数据方式对齐
        tmpRect.setX(rect.x()+10);
        tmpRect.setWidth(tmpRect.width()-10);
        int nAlignment = this->model()->data(this->model()->index(0,logicIndex),Qt::TextAlignmentRole).toInt();
        painter->drawText(tmpRect,nAlignment,m_headerLst.at(logicIndex));
    }

    painter->restore();

}



bool HCommonHeaderView::getBSortFlag() const
{
    return bSortFlag;
}

void HCommonHeaderView::setBSortFlag(bool value)
{
    bSortFlag = value;
}

void HCommonHeaderView::setShowBottonLine(bool value)
{
    mbShowBottonLine = value;
}

void HCommonHeaderView::setAllColumnAligFlag(bool flag)
{
    bAllColumnAlgFlag = flag;
}

void HCommonHeaderView::setHeaderText_NoSort(const QStringList &list)
{
    m_headerLst.clear();
    m_headerLst = list;
}

 

正常的我们只需重写这个函数PaintSection,官方文档这样说明

[virtual protected] void QHeaderView::paintSection(QPainter *painter, const QRect &rect, int logicalIndex) const
Paints the section specified by the given logicalIndex, using the given painter and rect.
Normally, you do not have to call this function.

所以我们必须重写这个纯虚的保护函数,在里面进行自己的实现!并且不需要调用,Qt的官方API实现了当界面出来时候,自用调用;这里我重写了,进行了对图片,文本,已经线条的绘制。

 

既然是MVC,View我们已经实现了,这里我们必须重写QAbstractTableModel,自己重写这个类,实现自己的Model;

QAbstractTableModel类提供了一个抽象模型,可以对其进行子类化以创建表模型。

QAbstractTableModel为将数据表示为二维项数组的模型提供了标准接口。它不是直接使用的,但必须是子类。

由于该模型提供了比qabstractemmodel更专业的接口,因此它不适合与树视图一起使用,尽管它可以用于向QListView提供数据。如果需要表示一个简单的项列表,并且只需要一个模型来包含一列数据,那么子类化QAbstractListModel可能更合适。

rowCount()和columnCount()函数返回表的维度。要检索与模型中某个项对应的模型索引,请使用index()并仅提供行号和列号。

对于重写这个类,我们必须重写一下六个虚函数!

[virtual] QVariant QAbstractItemModel::headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const

Returns the data for the given role and section in the header with the specified orientation.

For horizontal headers, the section number corresponds to the column number. Similarly, for vertical headers, the section number corresponds to the row number.

官方解释:返回头中具有指定方向的给定角色和节的数据。对于水平标题,节编号对应于列编号。类似地,对于垂直标题,节编号对应于行编号。

这里进行了实现,返回表头的指定方向指令角色的数据

QVariant BDPortfolioNewModel::headerData(int section, Qt::Orientation orientation, int role) const
{
    if(section > mHeaderLst.size() || section == mHeaderLst.size() || section < 0)
    {
        return QVariant();
    }
    if( orientation == Qt::Horizontal && role == Qt::DisplayRole )
    {
        return mHeaderLst.at(section);
    }
    else if (orientation == Qt::Horizontal && role == Qt::TextAlignmentRole)
    {
        return QVariant(Qt::AlignHCenter|Qt::AlignVCenter);
    }
    else if (orientation == Qt::Horizontal && role == Qt::TextColorRole)
    {
        return  QColor("#ffffff");
    }
    else
    {
        return  QVariant();
    }
}

二:

[virtual] bool QAbstractItemModel::setHeaderData(int section, Qt::Orientation orientation, const QVariant &value, int role = Qt::EditRole)

Sets the data for the given role and section in the header with the specified orientation to the value supplied.

Returns true if the header's data was updated; otherwise returns false.

When reimplementing this function, the headerDataChanged() signal must be emitted explicitly.

官方说明:将头中具有指定方向的给定角色和节的数据设置为提供的值。如果更新了头的数据,则返回true;否则返回false。重新实现此函数时,必须显式发出headerDataChanged()信号。

也就是设置表头信息

bool BDPortfolioNewModel::setHeaderData(int section, Qt::Orientation orientation, const QVariant &value, int role)
{
    if(section > mHeaderLst.size() || section == mHeaderLst.size() || section < 0)
    {
        return false;
    }
    if(orientation != Qt::Horizontal) return false;
    if(role == Qt::DisplayRole){
        mHeaderLst[section]  = value.toString();
        return true;
    }
    return false;
}

三:

[pure virtual] int QAbstractItemModel::rowCount(const QModelIndex &parent = QModelIndex()) const

Returns the number of rows under the given parent. When the parent is valid it means that rowCount is returning the number of children of parent.

这个表有多少行数:

int BDPortfolioNewModel::rowCount(const QModelIndex &parent) const
{
    return mFiliterData.count();
}

四:

[pure virtual] int QAbstractItemModel::columnCount(const QModelIndex &parent = QModelIndex()) const

Returns the number of columns for the children of the given parent.

In most subclasses, the number of columns is independent of the parent.

For example:

int DomModel::columnCount(const QModelIndex &/*parent*/) const

  {
      return 3;
  }
Note: When implementing a table based model, columnCount() should return 0 when the parent is valid.

整个表有多少列:

int BDPortfolioNewModel::columnCount(const QModelIndex &parent) const
{
    return mHeaderLst.count();
}

 

五:

[pure virtual] QVariant QAbstractItemModel::data(const QModelIndex &index, int role = Qt::DisplayRole) const

Returns the data stored under the given role for the item referred to by the index.

Note: If you do not have a value to return, return an invalid QVariant instead of returning 0.

返回index指定角色的数据

///
/// \brief BDPortfolioNewModel::data
/// \param index
/// \param role
/// \return
///数据设置和显示
QVariant BDPortfolioNewModel::data(const QModelIndex &index, int role) const
{
    if(!index.isValid())
    {
        return QVariant();
    }
    switch (role)
    {
    case Qt::DisplayRole:{
        return itemDisplayRole(index);
    }break;
        //    case Qt::TextColorRole:{
        //        return itemForegroundRole(index);
        //    }break;
    case Qt::TextAlignmentRole:{
        return itemTextAlignmentRole(index);
    }break;
    case Qt::ToolTipRole:{
        QString tip = index.data().toString();
        return tip;
    }break;
        //    case Qt::UserRole:{
        //        return itemUserRole(index,role);
        //    }break;
    case (Qt::UserRole):{
        if(index.column()==ENTRUST_DIR){
            return  (int)mFiliterData[index.row()].nEntrustDir;
        }
        else
            return mFiliterData[index.row()].strSecurityCode;
    }break;
    case(Qt::UserRole+2):{
        if(strSelectkID == mFiliterData[index.row()].strSecurityCode)
            return true;
        else false;
    }
    default:
        return QVariant();
    }
    return QVariant();

}

六:

[virtual] bool QAbstractItemModel::setData(const QModelIndex &index, const QVariant &value, int role = Qt::EditRole)

Sets the role data for the item at index to value.

Returns true if successful; otherwise returns false.

The dataChanged() signal should be emitted if the data was successfully set.

设置指定位置指定角色的数据,当设置成功发出dataChange()信号!

bool BDPortfolioNewModel::setData(const QModelIndex &indexData, const QVariant &value, int role)
{
    if (!indexData.isValid()) return false;
    if(indexData.column() == SECYRITYCODE && (role == Qt::UserRole)){
        if(!judgeLegalCode(value.toString())) return false;

        for(int i = 0; i< mSrcData.count(); i++) {
            BDNewPortfolioData var = mSrcData.at(i);
            if(var.strSecurityCode ==  mFiliterData[indexData.row()].strSecurityCode){
                mSrcData[i].strSecurityCode = value.toString();
                break;
            }
        }
        if(strSelectkID == mFiliterData[indexData.row()].strSecurityCode)
            strSelectkID = value.toString();
        mFiliterData[indexData.row()].strSecurityCode = value.toString();
        emit dataChanged(index(indexData.row(), SECYRITYCODE), index(indexData.row(), SECYRITYCODE));

        return true;
    }else if(indexData.column() == SECURITYNAME){
        mFiliterData[indexData.row()].strSecurityName = value.toString();
        setColumnSrcData(mFiliterData[indexData.row()].strSecurityCode,SECURITYNAME,value);
        emit dataChanged(index(indexData.row(), SECURITYNAME), index(indexData.row(), SECURITYNAME));
        return true;

    }else if(indexData.column() == NUMBER || indexData.column() == RELWEIGHT){

        if(indexData.column() == NUMBER){
            mFiliterData[indexData.row()].llCodeNumber = (value.toString()).toLongLong();
            mFiliterData[indexData.row()].bWeightFlag = (mFiliterData[indexData.row()].llCodeNumber == 0)?true:false;
        }else if(indexData.column() == RELWEIGHT){
            mFiliterData[indexData.row()].dRelativeWeight = (value.toString()).toDouble();
            mFiliterData[indexData.row()].bWeightFlag = (mFiliterData[indexData.row()].dAbsoluteWeight == 0)?false:true;
        }

        setColumnSrcData(mFiliterData[indexData.row()].strSecurityCode,indexData.column(),value, mFiliterData[indexData.row()].bWeightFlag);
        //judgetItemFlag(); //查询item的flag;
        emit dataChanged(index(indexData.row(), indexData.column()), index(indexData.row(), indexData.column()));
        return true;
    }
    else if(indexData.column() == PREHARVEST || indexData.column() == LIMITUP || indexData.column() == LIMITDWON)
    {
        if(indexData.column() == PREHARVEST)
        {
            mFiliterData[indexData.row()].dPreharvest = (value.toString()).toDouble();
        }
        else if(indexData.column() == LIMITUP)
        {
            mFiliterData[indexData.row()].dLimit_up = (value.toString()).toDouble();
        }
        else if(indexData.column() == LIMITDWON)
        {
            mFiliterData[indexData.row()].dLimit_dwon = (value.toString()).toDouble();
        }
        emit dataChanged(index(indexData.row(), indexData.column()), index(indexData.row(), indexData.column()));
        return true;
    }else  if(indexData.column()==ENTRUST_DIR && (role == Qt::UserRole)){

        mFiliterData[indexData.row()].nEntrustDir =(ENTRUSTDIR)(value.toInt()) ;
        setColumnSrcData(mFiliterData[indexData.row()].strSecurityCode,ENTRUST_DIR,value);
        emit dataChanged(index(indexData.row(), indexData.column()), index(indexData.row(), indexData.column()));

        return true;
    }

    return false;
}

最后这个函数也很重要 beginResetModel();

开始模型重置操作。重置操作将模型重置为任何附着视图中的当前状态。

注意:附加到此模型的任何视图也将被重置。当模型重置时,这意味着从模型报告的任何以前的数据现在都无效,必须再次查询。这也意味着当前项和任何选定项都将无效。

当模型从根本上更改其数据时,有时更容易调用此函数,而不是在底层数据源或其结构发生更改时发出data changed()通知其他组件。重置模型或代理模型中的任何内部数据结构之前,必须调用此函数。此函数发出信号modelAboutToBeReset()。

紧接着 endResetModel();

完成模型重置操作。重置模型或代理模型中的任何内部数据结构后,必须调用此函数

 

调用创建的代码如下:

mHeaderView = new HCommonHeaderView(Qt::Horizontal,this);
    mHeaderView->setStretchLastSection(true);
    mHeaderView->setAllColumnAligFlag(true);
    mHeaderView->setShowBottonLine(true);
    mHeaderView->setTextAlign(4);
    mHeaderView->setBSortFlag(false);
    mpModel = new BDPortfolioNewModel(ui->tableView);

    ui->tableView->setObjectName("portfolioNewTableView");
    ui->tableView->setFocusPolicy(Qt::NoFocus);
    ui->tableView->horizontalHeader()->setStretchLastSection(true);
    ui->tableView->horizontalHeader()->setHighlightSections(true);
    ui->tableView->verticalHeader()->setVisible(true);
    ui->tableView->verticalHeader()->setDefaultSectionSize(28);
    ui->tableView->setShowGrid(true);
    ui->tableView->setMouseTracking(false);
   // ui->tableView->setFrameShape(QFrame::NoFrame);
    ui->tableView->setEditTriggers(QAbstractItemView::AllEditTriggers);
    ui->tableView->setSelectionBehavior(QAbstractItemView::SelectRows);

    ui->tableView->setModel(mpModel);

    mHeaderView->setHeaderText_NoSort(mpModel->getHeaderDataLst());
    mHeaderView->setStretchLastSection(false);
    ui->tableView->setHorizontalHeader(mHeaderView);

    mpDelegate = new BDPorfolioNewDelegate(this);
    ui->tableView->setItemDelegate(mpDelegate);

实现的效果图如下

源码路径:https://download.csdn.net/my

  • 4
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

漫天飞舞的雪花

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值