PDA

View Full Version : QTableView: rowAt() gives wrong row number (aim: right-cklick enabling)



sedi
18th July 2012, 14:57
Hi,
I have an ui->tableView (set up with designer) and subclassed a QStandardItemModel to attach it, along with aQSortFilterProxyModel.

I want to make the items right-cklickable for a context menu. It nearly works - apart from a very annoying offset in the heigth that amounts to roughly half of a row's height. When I right-click an item in it's bottom half, the item below is given back.

In the dialog's constructor:


this->proxyModel = new QSortFilterProxyModel();
proxyModel->setSourceModel(fotoImport); //foto Import is the model
proxyModel->setDynamicSortFilter(true);
ui->tableView->setModel(proxyModel);
ui->tableView->resizeColumnsToContents();
ui->tableView->resizeRowsToContents();
ui->tableView->verticalHeader()->hide();
ui->tableView->setSortingEnabled(true);


In the dialog's contextMenuEvent (QContextMenuEvent *e) I try this:


QPoint pos;
pos=ui->tableView->mapFrom(this,e->pos());
int row=ui->tableView->rowAt(pos.y());
int column=ui->tableView->columnAt(pos.x());
if (row==-1)return;
if (column==-1)return;
QModelIndex index=ui->tableView->indexAt(pos);
QModelIndex proxyIndex;
proxyIndex=this->proxyModel->mapToSource(index);
qDebug()<<"map from this: "<<fotoImport->itemFromIndex(proxyIndex)->text();


It furthermore might be important that my model contains small pictures.

I've set them up this way in the model:


item->setData(myPixmap.scaledToHeight(50,Qt::SmoothTrans formation),Qt::DecorationRole);


Instead of
pos=ui->tableView->mapFrom(this,e->pos());
I've also tried
pos=ui->tableView->mapFromParent(e->pos());
which gives equal results and
pos=ui->tableView->mapFrom(ui->tableView, e->pos());

as well as all other mapFromXXX and mapToXXX possibilities.

The columnAt() works fine.

Any idea what I am doing wrong?

wysota
18th July 2012, 16:59
The position is given relative to the view's viewport(), not to the view itself. Thus the "annoying offset".

sedi
18th July 2012, 17:17
Smack dab in the middle, wysota - as usual. Thank you!

pos=ui->tableView->viewport()->mapFromGlobal(e->globalPos());
did the trick.