双击QTreeView将始终返回第一列值

时间:2015-07-10 14:06:35

标签: qt qt5 qtreeview

我有 QTreeView ,其中选择了整行:

  ui->treeView->setSelectionBehavior (QAbstractItemView::SelectRows);

...已经填写了ID-Number< - >描述。所有都是树的结构。我可以点击它,并通过以下方式检索相应的选择:

ui->lineEdit->setText( modelIndex.data(Qt::DisplayRole).toString() );

我已经联系了:

  connect(ui->treeView, SIGNAL(doubleClicked(QModelIndex)), this, SLOT(onSelectedTreeView(QModelIndex)));

当我点击ID-Number时,它完美运行,我的modelIndex.data()返回ID-Number。

当我点击描述时,我的modelIndex.data()会返回正确的描述(第二列)。但我想再次提供相应的ID号码(第一栏)。

我感谢任何帮助。提前谢谢。

2 个答案:

答案 0 :(得分:0)

您可以使用sibling(int row, int column)

QModelIndex方法

在python中:

def onSelectedTreeView(index):
    firstColumnIndex=index.sibling(index.row(),0)
    print(firstColumnIndex.data())

我想你可以做到:

ui->lineEdit->setText(modelIndex.sibling(modelIndex.row(),0).data(Qt::DisplayRole).toString());

答案 1 :(得分:0)

您可以将treeView selectionBehavior更改为SelectItems。比使用index.row()和index.column()..并且不要忘记它总是从0开始

onSelectedTreeView()
{
    //Put all your selected indexes into QModelIndexList
    QModelIndexList _indexes = ui->treeView->selectionModel()->selectedIndexes();

    // For each loop for every selected index.. 
    foreach (QModelIndex index, _indexes)
    {

    //if your index data == 0 it means that you clicked into ID-number field.

   //So you can easly see which index you clicked with qdebug
   qDebug() << "Row = " << index.row() << "\t Column = " << index.column();

   // So if you want to get always index of first column(ID-Number) use QAbstractItemModel
   if(index.column().toInt() != 0 ) //if your index not equal to 0
   {
      const QAbstractItemModel* absModel = index.model();

      // change index of absModel from index.column() to 0;
     QModelIndex changedIndex = absModel->data(absModel->index(index.row(), 0), Qt::DisplayRole).toInt();

     qDebug() << "Row = " << changedIndex.row() << "\t Column = " << changedIndex.column();
   }

   }
}