0
votes

I'm new to Qt. i want to cast a row item in the QTableWidget as object.

So far, i've manage to populate the QTableWidget with QList:

header.h
QList<Inventory> inventories;

int row = 0;
int rowCount  = ui->tableItems->rowCount();

ui->tableItems->insertRow(rowCount);

foreach(Inventory inventory, this->inventories)
{

    QTableWidgetItem *code = new QTableWidgetItem(inventory.getName());
    QTableWidgetItem *name = new QTableWidgetItem(inventory.getCode());
    QTableWidgetItem *price = new QTableWidgetItem(GlobalFunctions::doubleToMoney(this, inventory.getPrice()));

    ui->tableItems->setItem(row,0,code);
    ui->tableItems->setItem(row,1,name);
    ui->tableItems->setItem(row,2,price);       

    row++;
}

In my table, i will select the row using this. enter image description here

void CreateSalesWindow::removeItem()
{
    qDebug() << "Remove Item" << ui->tableItems->currentIndex().column();
    this->salesdetails.removeAt(ui->tableItems->currentIndex().column() - 1);
    this->refreshItemList();
}

I've manage to get the selected row, is there a straightforward way to cast my row back into object. I've come from a C# .Net Background where i could easily cast it back into something like this (just an example). I could not found any good solutions in SO and Documentation.

Inventory selectedInventory = (Inventory) ui->tableItems->selectedItem().getValue();

qDebug() << selectedInventory.getPrice();
// 1699.75

PS. I also want to remove an item from the QList<> from the selected row in the table.

Thanks! I'm new to Qt, i'm open to much better approach in handling this. if something is unclear please raise a comment so i could correct it.

1

1 Answers

1
votes

I'm not familiar with the QTableWidget itself, but in general you should use the row method with Qt's model/view classes to access the underlying data row index of the model and then just access your original data from your custom model (depending on the implementation of your model).

In your case something like this:

int rowIndex = ui->tableItems->selectedItems().first().row();
// or this should also work to get the current index directly
int rowIndex = ui->tableItems->currentIndex().row();
Inventory *selectedInventory = ui->tableItems->model()->getInventory(rowIndex);

where the getInventory(int index) method is your custom method to access your object via its index (I guess you have a derived model from QAbstractItemModel or something so save your data and view it in the QTableWidget).

That is at least what I would do, you can read more about general model/view programming with Qt at Introduction to Model/View Programming.