Reading value from a cell in a tableView created by QStandardItemModel



  • Hi,
    I have a table created by QStandardItemModel. on_tableview_clocked tells me the item the user clicked. I need to read the the first column (column 0) ID. Here is the code I currently have:

    void MainWindow::on_tableView_clicked(const QModelIndex &index)
    {
        int row = index.row ();
        int column = index.column ();
        qDebug() << "Index: " << "(" << row <<"," << column << ")";
    
        if(column == 2)
            {
                qDebug() << "Column 2 was chosen.";
    
                QPixmap imageToEnlarge = index.data(Qt::DecorationRole).value<QPixmap>();
    
                int w = ui->label_Temp->width();
                int h = ui->label_Temp->height ();
                ui->label_Temp->setPixmap (imageToEnlarge.scaled(w,h,Qt::KeepAspectRatio));
                ImageDisplay *mImageDisplay = new ImageDisplay;
                mImageDisplay->viewImage(imageToEnlarge);
                mImageDisplay->exec ();
    
            }
    }
    

    How can I get the value from column 0 knowing the row number from

      int row = index.row ();
    

    Thank you.


  • Moderators

    @gabor53
    Create a QModelIndex using existing index that you get in onClicked slot. This index will give you row whereas you have the column. Once you get the new index use data with your required role perhaps Qt::DisplayRole unless you have your user defined roles. So to sum up:

    QModelIndex newindex(index.model()->index(index.row(), 0, index.parent())); //0th column 
    qDebug() << newindex.data(Qt::DisplayRole);
    


  • Thank you. It worked perfectly.



  • @p3c0
    How can I assign the value displayed by qDebug to a QString or int?
    Thank you.


  • Moderators

    @gabor53 The data function returns a QVariant. You need the convert the returned value into your required type. QVariant has several built-in methods to do so. Have a look at those starting with to*.
    http://doc.qt.io/qt-5/qvariant.html#toString
    http://doc.qt.io/qt-5/qvariant.html#toInt



  • @p3c0
    I came up with the following and it works great:

                QModelIndex newindex(index.model()->index(index.row(), 0, index.parent()));
                qDebug() << newindex.data(Qt::DisplayRole);
                QVariant v(newindex.data(Qt::DisplayRole));
                FriendID = v.toString ();
                qDebug () << "Friend ID: " << FriendID;
    

    Thank you for your help.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.