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?
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.
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? 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 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.
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.
Use the currentRowChanged(const QModelIndex & current, const QModelIndex & previous)
signal from the selection model (docs).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With