0

Being new to Qt. I wanted to know if there was a way to add a primary key in a QtableWidget.The reason I want to do this is because I want to create a mechanism so that if I add a row with a key that is not in the table it gets added as a new row otherwise the existing row with that key gets updated.Any suggestions on how I could accomplish this ?

MistyD
  • 16,373
  • 40
  • 138
  • 240

2 Answers2

0
        // Assuming m_table of QTableWidget* type
        // Assuming single column

        const int rowCount = m_table->rowCount();
        if(rowToInsert < rowCount)
        { 
           m_table->setItem(rowToInsert, 0, /* your data */ );
        }
        else
        {
          m_table->setRowCount(rowCount + 1);
          m_table->setItem(rowCount + 1, 0, /* your data */ );
        }
Arun
  • 2,087
  • 2
  • 20
  • 33
0

Use QTableWidgetItem::setData ( int role, const QVariant & value ) method to set your data (primary key) with custom role, and QVariant QTableWidgetItem::data ( int role ) to retreive it. role should be Qt::UserRole or any number higher than 32. See reference for QTableWidgetItem::setData(int role, const QVariant & value) for more info.

And if you're new to Qt, you should look for Qt model/view, in your case it can be smart to do your check in model and display model's data in QTableView instead of QTableWidget.

SpongeBobFan
  • 964
  • 5
  • 13