Important: Please read the Qt Code of Conduct -

QTableWidget: How can I get the row and column index when user click on a particular cell using single mouse click?

  • I have created a TableWidget inside i have tale 4 row and 5 column. Now, I want to select particular row and column place where i can apply some another event. Here my peace of code for creating dynamically QTableWidget at proper place.

     QTableWidget *twidget = new QTableWidget(this);
    	"background-color: lightgray;"
    twidget->setGeometry(114, 70, 200, 98);
    for (auto r = 0; r < 4; r++) {
    	for (auto c = 0; c < 5; c++) {
    		QTableWidgetItem *item = new QTableWidgetItem(QString::number(r + 1) + "x" + QString::number(c + 1));
    		item->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled);
    		twidget->setItem(r, c, item);
    		//twidget->setItem(r, c, new QTableWidgetItem(QString::number(r+1) + "x" + QString::number(c+1)));

    Now I want to get the index of place wehere i can apply signal and slot to processing on the place.

    Thanku in advance


    connect(twidget,&QAbstractItemView::clicked,this,[](const QModelIndex& idx)->void{
    qDebug() << "Clicked: " << idx.row()<<","<<idx.column();


    twidget->setGeometry(114, 70, 200, 98);

    not a fan of this, any reason why you are not using a layout?

  • @VRonin I want to create one slot method where i can get row and column . inside the slop function i am using signal and slot to fix the proper method.
    Also i am used this one connect signal but this one not working.

    connect(twidget, SIGNAL(cellClicked(int, int)), this, SLOT(previousWeek(int, int)));

  • If you are using Qt5 you should move to the New connect syntax.

    change previousWeek from a slot that takes 2 ints to 1 that takes 1 const QModelIndex&
    then use connect(twidget, SIGNAL(clicked(QModelIndex)), this, SLOT(previousWeek(QModelIndex)));.

    you can then use QModelIndex::row() and QModelIndex::column() to find out the coodinates of the clicked item

  • @VRonin said in QTableWidget: How can I get the row and column index when user click on a particular cell using single mouse click?:

    connect(twidget, SIGNAL(clicked(QModelIndex)), this, SLOT(previousWeek(QModelIndex)));.

    When i do this one in constructure then i will getting exception
    "Exception thrown at 0x00007FFAEB2F352C (Qt5Cored.dll) in RadSpaEngine.exe: 0xC0000005: Access violation reading location 0xFFFFFFFFFFFFFFFF."

  • Seems like you are accessing a dangling/unassigned pointer. where did you put the connect?

  • @VRonin Now i get the problem? Thanku for responding me

Log in to reply