Joseph
Joseph

Reputation: 13198

Qt/C++: QTableView contextmenu and passing through information

I want a contextmenu on the cells in my QTableView, so first I connected:

connect(ui->tblTimesheet,SIGNAL(customContextMenuRequested(QPoint)),this,SLOT(sheetContextMenu(const QPoint &)));

And the slot for that connect is below:

void wndMyWindow::sheetContextMenu(const QPoint &pos){
    QMenu *menu = new QMenu;
    QModelIndex cell = ui->tblTimesheet->indexAt(pos);
    // Make sure the right click occured on a cell!
    if(cell.isValid()){
        QString myid=cell.sibling(cell.row(),0).data().toString();
        menu->addAction("Remove item", this, SLOT(sheetRemoveItem()));
        menu->exec(ui->tblTimesheet->mapToGlobal(pos));
    }
}

Which creates the menu and puts an action in the menu which calls a function when that action is clicked. However, I want to pass through the variable myid into the second slot. That slot is listed below:

void wndMyWindow::sheetRemoveItem(){
    qDebug("Sure I'm here, but what info do I have?");
    return;
}

I'm not quite sure how to do this, can anyone help?

Upvotes: 1

Views: 3068

Answers (2)

chikuba
chikuba

Reputation: 4357

After reading the previous answer, I realized that you can actually attach some data on to the sender. I do it in my code.

Every objects that inherits from QObject has "setProperty()". Here you can set some data before it starts sending signals. In one of my slots I do the following:

qobject_cast<QAction*>(sender())->property("index").toInt()

This allows me to attach an index to my action.

Upvotes: 1

Edward Strange
Edward Strange

Reputation: 40897

In this regard, Qt signals/slots suck compared to callbacks and other signal/slot mechanisms. You really can't attach extra information.

Couple things you can do though:

  1. Create an object that stores the information you want to send, give it a slot and attach to the signal you want to respond to, emit a new signal with the information, attach to that signal.

  2. Use the Qt signal map thingy to attach some small variation of data to a signal.

  3. You can get the sender in a Qt slot. This may be the information you need. (see the Qt docs on signals/slots).

If none of those methods work for you, sorry to say but, you're pretty much fscked. I'm working on a method to auto-create #1 and attach to a boost::signal, which would be more powerful, but it's going to require a lot of hard work because Qt is incompatible with the C++ preprocessor and with templates.

Good luck.

Upvotes: 2

Related Questions