PDA

View Full Version : problem with Context Menu in QTableWidget



andreime
3rd August 2009, 07:43
Hello. I am trying to make a right click context menu appear over an item inside a QTableWidget.
I tried several things, but somehow it is not working or, not working properly.

void fileHandler::ctxMenu(const QPoint &pos)//started
{
QMenu *menu = new QMenu;
menu->addAction(tr("Test Item"), this, SLOT(test_slot()));
menu->addSeparator();
menu->addAction(tr("Test Item"), this, SLOT(test_slot()));
menu->exec(m_ui->tableWidget->mapToGlobal(pos));
}
In the constructor i am doing this:

connect(m_ui->tableWidget, SIGNAL(customContextMenuRequested(const QPoint &)), this, SLOT(ctxMenu(const QPoint &)));
The problem with this thing is that when i right click on an item the popup menu appears not next to the x,y coordinates of where i clicked but somewhat x+50 px or so(only for the example i have). i also want to have a context menu only on items. I couldn't find anything to work like i want.
I want to add operations with fast navigation using the context menu for selected item or items. Thank you.

victor.fernandez
3rd August 2009, 09:06
Did you try this? :


menu->exec(QCursor::pos());

andreime
3rd August 2009, 09:48
genius... it works like a charm ! thank you.
now for the other part.. how do you think i should check and allow the context menu to appear only when i click on a TableWidgetItem?

victor.fernandez
3rd August 2009, 10:01
You may get the index at the cursor position and check whether it's valid:


void fileHandler::ctxMenu(const QPoint &pos)//started
{
QModelIndex index = m_ui->tableWidget->indexAt(pos);
if(!index.isValid())
return;

QMenu *menu = new QMenu;


Another way, getting the QTableWidgetItem:


void fileHandler::ctxMenu(const QPoint &pos)//started
{
QTableWidgetItem *item = m_ui->tableWidget->itemAt(pos);
if(!item)
return;

QMenu *menu = new QMenu;

numbat
3rd August 2009, 10:22
The documentation for customContextMenuRequested states:

Normally this is in widget coordinates. The exception to this rule is QAbstractScrollArea and its subclasses that map the context menu event to coordinates of the viewport() .
Note that QTableWidget indirectly derives from QAbstractScrollArea. So you have to use


menu->exec(m_ui->tableWidget->viewport()->mapToGlobal(pos));

This is a little neater than using the current mouse position as the cursor may have moved on by the time you receive the event.

andreime
3rd August 2009, 10:44
thank you alot for the help

sebekmez
7th September 2015, 08:44
Many Thanks numbat !
Only menu->exec(m_ui->tableWidget->viewport()->mapToGlobal(pos)); works correctly.