How does Qt make a cell in QTableWidget store some value, but at the same time display other information, the value of which depends on the stored information in the cell? Roughly speaking, a cell with an index (1: 1) (cell [1] [1]) stores a value of type int, for example the number 7, and displays a string of type QString "test_cell".

    2 answers 2

    Use QTableWidgetItem::setData(int role, const QVariant &value)

     QTableWidgetItem *item = new QTableWidgetItem; item->setText("text"); item->setData(Qt::UserRole, 42); ui->tableWidget->setItem(0,0,item); 

    The text will be displayed, and 42 data will lie in the cell as data. You can put several user variables in one cell, using Qt:UserRole + 1 , Qt:UserRole + 2 , etc. as the role .

    Take data from a cell:

     QVariant v = item->data(Qt::UserRole); 

      As an option, you can set your delegate through setItemDelegate and in it implement the display of everything your heart desires, for example, replacing the QStyleOptionViewItem :: text value with your own in the paint method. But then you still have to process setEditorData and setModelData so that the value is correctly converted before and after editing in the cell.

      • I actually do this. I wrote my own combobox, inheriting from ComboBoxItemDelegate. wiki.qt.io/Combo_Boxes_in_Item_Views - Anton
      • in void ComboBoxItemDelegate :: setModelData (...) through model-> setData I set the required value. Do I understand correctly that I need to "redraw a cell" right after executing this instruction? - Anton
      • It's not completely clear what kind of paint method you mean, which class's method? I just can't find it in QTableWidget or in QAbstractItemModel. - Anton
      • It's about QAbstractItemDelegate::paint . If done correctly, you do not need to redraw anything. It will cause paint itself. But inside it you can already replace the text with your own and transfer the changed data to the base class. - nrw
      • Something like this: QStyleOptionViewItem my_option = option; my_option.text = "my text"; QStyledItemDelegate::paint(painter,my_option,index); QStyleOptionViewItem my_option = option; my_option.text = "my text"; QStyledItemDelegate::paint(painter,my_option,index); - nrw