2012-01-08 5 views
1

다음은 내 사용자 정의 테이블 모델입니다. 그 테이블 모델을 QTableView와 함께 사용하려고합니다. 테이블 모델의 append 메서드를 호출하면 테이블 뷰에서 해당 내용을 업데이트 할 것으로 예상됩니다. 하지만 그 이유는 모르겠다. 그러나 동일한 테이블 모델을 QListView와 함께 사용하면 테이블 모델의 추가가 호출 될 때 목록보기에서 해당 내용을 업데이트합니다. QTableView의 경우에해야 할 특별한 것이 있습니까?QTableView가 dataChanged 신호에 반응하지 않는 것 같습니다.

class MyModel : public QAbstractTableModel 
{ 
public: 

    MyModel(QObject* parent=NULL) : QAbstractTableModel(parent) {} 

    int rowCount(const QModelIndex &parent = QModelIndex()) const { 
     return mData.size(); 
    } 

    int columnCount(const QModelIndex &parent = QModelIndex()) const { 
     return 2; 
    } 

    QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const { 
     if (!index.isValid()) { 
      return QVariant(); 
     } 

     if (role == Qt::DisplayRole) { 
      if (index.column()==0) { 
       return QVariant(QString::fromStdString(getFirst(index.row()))); 
      } 
      if (index.column()==1) { 
       return QVariant(QString::fromStdString(getSecond(index.row()))); 
      } 
     } 

     return QVariant(); 
    } 

    void append(std::string const& first, std::string const& second) { 
     mData.push_back(std::make_pair(first, second)); 

     emit dataChanged(index(mData.size()-1, 0), index(mData.size()-1, 1)); 
    } 

    std::string const& getFirst(int i) const { 
     return mData[i].first; 
    } 

    std::string const& getSecond(int i) const { 
     return mData[i].second; 
    } 

protected: 

    std::vector<std::pair<std::string, std::string> > mData; 
}; 

답변

3

새 행을 삽입하는 대신 기존 데이터를 변경하고, 당신은 대신 beginInsertRows 및 endInsertRows를 사용한다 : 그 도움이된다면

void append(std::string const& first, std::string const& second) { 
    int row = mData.size(); 
    beginInsertRows(QModelIndex(), row, row); 

    mData.push_back(std::make_pair(first, second)); 

    endInsertRows(); 
} 

참조.

+1

이렇게하면 도움이되었습니다. 이 답변을 발견 한 문서에 대한 링크가 있습니까? – qwerty9967

+0

beginInsertRows/endInsert 행의 사용법은 [QAbstractItemModel 클래스] (http://qt-project.org/doc/qt-4.8/qabstractitemmodel.html#beginInsertRows)의 Qt 문서에서 찾을 수 있습니다. – JediLlama