Question

How should this be done by using the model->setData() method call?

I have derived a class called "MyStandardItemModel" from QStandardItemModel. I have made my third and fourth columns non-editable by overriding the protected virtual flags method. This is how it goes:

#define TX_PACKET_COLUMN (4u)
#define RX_PACKET_COLUMN (5u)

Qt::ItemFlags MyStandardItemModel::flags(const QModelIndex& index) const
{
    if (index.column() == TX_PACKET_COLUMN || index.column() == RX_PACKET_COLUMN)
    {
        return (QStandardItemModel::flags(index) & ~Qt::ItemIsEditable);
    }
    else
    {
        return QStandardItemModel::flags(index);
    }
}

...

//Set model
ui->testCaseTableView->setModel(model);

Having this done, I am not able to edit the cells in the third and fourth column.

Now, I want that when I double click on these cells, a pop-up dialog comes up. I will modify some data in the editable field of that dialog, and then copy it back to the non editable cells inside the code.

I tried to just write a doubleclick() handler for the QTreeView and just copy some data to the cells just to see if it is possible to copy data to the non-editable cells.

This operation is failing, and the data is not written into the non-editable cells.

Here you can find the double click handler:

void MainWindow::on_testCaseTableView_doubleClicked(const QModelIndex &index)
{
    QVariant variant;
    variant.toString() = "AA";

    if((index.column() == TX_PACKET_COLUMN)||(index.column() == RX_PACKET_COLUMN))
    {
        model->setData(index, variant);   // set new value
    }

}

The setData(..) operation is clearing the already written data in the cells, but string "AA" is not getting written. Please suggest how to copy some data to non-editable cells inside the code.

enter image description here

Was it helpful?

Solution 2

As I indicated in my comment, you have to fix this first issue:

instead of:

QVariant variant;
variant.toString() = "AA";

you should write

QVariant variant = QLatin1String("AA");

In general, you would look into the setData(...) implementation for such cases whether you emit the data changed signal properly and so forth, but here you are entering a prior issue which can lead to problems, so let us fix that.

Note, you should use QLatin1String to avoid the unnecessary explicit conversion from raw char* to QString. This is a good practice in general, and this is available with Qt 4 as well as Qt 5.

Although, you could also use the QStringLiteral macro for creating a QString very efficiently with template magic out of your raw literal, but that requires C++11.

OTHER TIPS

QVariant set is empty. Nothing needs to be wrong in your model. Error is on this line:

variant.toString() = "AA";

change to:

QVariant variant("AA"); // just for testing anyway
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top