我有一个连接到QAbstractItemModel的rowsInserted SIGNAL的onText方法,因此我可以在插入新行时收到通知:

QObject::connect(model, SIGNAL(rowsInserted ( const QModelIndex & , int , int  )  ),
                        client_,SLOT(onText( const QModelIndex & , int , int  )) )

信号正常,因为插入行时会收到通知。这是onText方法:

void FTClientWidget::onText( const QModelIndex & parent, int start, int end ) 
{
    Proxy::write("notified!");

    if(!parent.isValid())
        Proxy::write("NOT VALID!");
    else
        Proxy::write("VALID");

     QAbstractItemModel* m = parent.model();


}

但我似乎无法从插入的项目中获取字符串。 QModelIndex“父”是指QModelIndex。传递不是有效的,而“m”是有效的。 QAbstractItemModel为NULL。我认为它是因为它不是一个实际的项目,而只是一个指针?如何获取插入的文本/元素?

有帮助吗?

解决方案

由于父级对于顶级项目无效,另一种选择是让FTClientWidget访问模型(如果它不违反您的设计),然后FTClientWidget可以直接使用开始和结束参数模特本身:

void FTClientWidget::onText( const QModelIndex & parent, int start, int end ) 
{
   //Set our intended row/column indexes 
   int row = start;
   int column = 0;

   //Ensure the row/column indexes are valid for a top-level item
   if (model_->hasIndex(row,column))
   {
      //Create an index to the top-level item using our 
      //previously set model_ pointer
      QModelIndex index = model_->index(row,column);

      //Retrieve the data for the top-level item
      QVariant data = model_->data(index);
   }
}

其他提示

父级对于顶级项目始终无效,因此您可能会认为它无效。 Qt文档有一个很好的解释确切地说父母的工作方式。 start 是插入子项的第一行, end 是插入子项的最后一行。

因此,您可以使用以下内容访问它:

int column = 0;

// access the first child
QModelIndex firstChild = parent.child(first, column);
QModelIndex lastChild = parent.child(end, column);

// get the data out of the first child
QVariant data = firstChild.data(Qt::DisplayRole);

或者,如果需要,您可以使用索引来检索可以从中访问它的模型。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top