使用更多行动态更新QTableView

时间:2013-02-15 07:35:06

标签: qt qtableview qabstracttablemodel

我有QTableView,它使用从QAbstractTableModel派生的模型。

模型以多行开始,并正确显示数据。

该模型还附有一个计时器,在到期时,获取行数和列数,为其构造索引,并发出dataChanged信号,以更新表的动态内容。

问题是当它应该显示的行数发生变化时。

在这种情况下,即使我获得了一个改变了no的新索引。行,并更新表,它仍然不显示任何新行。

我已经确定了原因。假设我在开头有2行,接下来,应该显示5行。在计时器到期逻辑中,我已经要求它构造一个新的索引,新行计数...但dataChanged()信号,只会更改已插入第一行的行的数据。不显示新行。

这是我的模型代码。

TableLayout::TableLayout()
  : QAbstractTableModel()
{
  rowCount();
  columnCount();
  timer = new QTimer(this);
  timer->setInterval(3000);
  timer->start();
  connect(timer, SIGNAL(timeout()), this, SLOT(timerHit()));

  //ItemList[0].SetFields("Blah" ,"Blah" , "Blah" , "Blah" , "Blah", "Blah", true  );
  //ItemList[1].SetFields("Blah1" ,"Blah1" ,"Blah1" ,"Blah1" ,"Blah1", "Blah1", true );
}

void TableLayout::timerHit()
{
  int row = this->rowCount();
  qDebug() << "RowCOunt::" << row;
  qDebug() << " Now IT IS : " << row;
  int col = this->columnCount();
  qDebug() << "ColumnCOunt::" << col;
  QModelIndex Ind = createIndex( 0, 0);
  QModelIndex Ind1 = createIndex( row, col);
  data(Ind1);
  emit dataChanged(Ind, Ind1);
}

int TableLayout::rowCount(const QModelIndex& /*parent*/) const
{
  RtdbReader* rtdbReader = RtdbReader::instance();
  if (isConnected)
    return rtdbReader->Get_Number_of_Items();
  else return 2;
}

int TableLayout::columnCount(const QModelIndex& /*parent*/) const
{
  return 6;
}

QVariant TableLayout::data(const QModelIndex& index, int role) const
{
  int row = index.row();
  int col = index.column();

  //return row;
  int row_count, col_count = 0;
  if ( role == Qt::DisplayRole) {

    if ( col == 1)
      return ItemList[row]->GetExplanation();
    if ( col == 2) {
      qDebug() << " Now printing Sig name for row" << index.row();
      return ItemList[row]->GetCond_Sig_Name();
    }
    if ( col == 3)
      return ItemList[row]->GetDescription();
    if ( col == 5)
      return ItemList[row]->GetLogic();
    if ( col == 4)
      return ItemList[row]->Get_State_Text();
  } else if ( role == Qt::DecorationRole && col == 0 ) {
    bool col_to_display = ItemList[row]->GetValueColour();
    qDebug() << "colour in view:" << col_to_display;
    if  ( col_to_display ) {
      QString path = "Green.png";
      //QPixmap p( s_type1Icon );
      // return s_type1Icon;

      QIcon icon ( path );
      return icon;
    } else {
      QString path = "Yellow.png";
      //QPixmap p( s_type1Icon );
      // return s_type1Icon;

      QIcon icon ( path );
      return icon;
    }
  }

  if (role == Qt::TextAlignmentRole )
    return Qt::AlignCenter | Qt::AlignVCenter;

  /* else if ( role == Qt::BackgroundRole)
   {
     QBrush yellowBackground(Qt::yellow);
              return yellowBackground;
   }*/

  return QVariant();
}

请建议我如何更改视图,以便添加新行。

感谢。

1 个答案:

答案 0 :(得分:-1)

仅仅因为您在QModelIndex处为元素创建row, col,并不意味着您为该元素创建了数据(也不是为当前结束与该元素之间的元素创建数据)。 / p>

您必须使用setData(...)向表中添加新数据,然后为视图发出dataChanged(...)以显示它。

相关问题