In a QGIS python plugin. I like to change value selected cell in qtablewidget to the typed value. Something like screenshot below.

enter image description here

But in changeattributevalue function. While column(second value) and string(third value) is really easy to get. I really can't find a way to get "QgsFeatureId"(first value) with row and columns of qtablewidget.

If I do something like below. It will always change wrong row.

layer.changeAttributeValue(long(table.selectedIndexes()[0].row()), table.selectedIndexes()[0].column(), changestring.text())

I tried to use QgsFeatureRequest() with unique column field, but I really don't know how to use this function with variables and scanning whole table seems ununnecessary.

(ex: request = QgsFeatureRequest().setFilterExpression( u' header[table.selectedIndexes()[0].column()] = table_data[0][table.selectedIndexes()[0].row()]' ))

Is there any way to get QgsFeatureId based on row number?

  • Feature ID is a row number in a "standard" QGIS table, so if you are sure your plugin does not do any sorting, you can just use it. I can't find any possibility how can you get fid if any of the data was sorted (during appending, calculating or whatever). After all, you just pasted a raw value into a table, so if they are unique, scanning every feature would be the only way. – adamczi Sep 23 '16 at 12:44
  • I didn't do any sorting and I'm sure about it. But above long(row()) doesn't work and edits some rows away from clicked cell. could there be something missing that I couldn't find? – GSaint Sep 23 '16 at 15:23
  • Well I think there is some kinda shaking things up while reading data from features. Gotta look into it. Thanks for your help! – GSaint Sep 23 '16 at 16:17

You need to save the feature ID when constructing QTableWidgetItem objects.

Qt gives you a handy method to store any data you need into a QTableWidgetItem (besides the displayed value).

item = QTableWidgetItem( someValue )
item.setData( Qt.UserRole, feature.id() )
self.mytable.setItem( row, column, item )

Once you have the selected item, you can retrieve such data in this way:

fid = item.data( Qt.UserRole )
  • Thanks! That surely solved the problem. It worked perfectly. – GSaint Sep 24 '16 at 9:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.