Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Qt: c++: How to create a SIGNAL/SLOT when selecting a row in QTableView

I have a QTableView which is working properly showing my model on the GUI. however, I would like to create a "SIGNAL/SLOT" that works when I select a row from the QTableView.

How can I do that?

like image 665
McLan Avatar asked Apr 23 '13 14:04

McLan


People also ask

How do you create a signal and slot in Qt?

There are several ways to connect signal and slots. The first is to use function pointers: connect(sender, &QObject::destroyed, this, &MyObject::objectDestroyed); There are several advantages to using QObject::connect() with function pointers.

Can we connect signal to signal in Qt?

This ensures that truly independent components can be created with Qt. You can connect as many signals as you want to a single slot, and a signal can be connected to as many slots as you need. It is even possible to connect a signal directly to another signal.

What is private slots in Qt?

What is private slots in Qt? Slots are a Qt-specific extension of C++. It only compiles after sending the code through Qt's preprocessor, the Meta-Object Compiler (moc). See http://doc.qt.io/qt-5/moc.html for documentation. Edit: As Frank points out, moc is only required for linking.

How does connect work in Qt?

How Connecting Works. The first thing Qt does when doing a connection is to find out the index of the signal and the slot. Qt will look up in the string tables of the meta object to find the corresponding indexes. Then a QObjectPrivate::Connection object is created and added in the internal linked lists.


2 Answers

You can do it in this way:

connect(ui->tableView->selectionModel(), SIGNAL(selectionChanged(const QItemSelection &, const QItemSelection &)),
             SLOT(slotSelectionChange(const QItemSelection &, const QItemSelection &))
            );

And the slot would be:

void MainWindow::slotSelectionChange(const QItemSelection &, const QItemSelection &)
{
            QModelIndexList selection = ui->tableView->selectionModel()->selectedRows();//Here you are getting the indexes of the selected rows

            //Now you can create your code using this information
}

I hope this can help you.

like image 88
Angie Quijano Avatar answered Oct 20 '22 10:10

Angie Quijano


Use the currentRowChanged(const QModelIndex & current, const QModelIndex & previous) signal from the selection model (docs).

like image 39
cmannett85 Avatar answered Oct 20 '22 08:10

cmannett85