Reputation: 191
Im looking for a clean way to react on the event if a QTableWidgetItem
has changed its text. I´ve tried to use the Signal QTableWidget::itemChanged(QTableWidgetItem *item)
but this causes an error due to the fact that i change the backgroundcolor of the QTableWidgetItem
in my slot and this slot is then executed recursivly, because the itemChanged.
I've also tried to use the signal QTableWidget::itemEntered(QTableWidgetItem *item)
but this is related to some mouse events which doesnt really work for me.
The last method I've tried is to override the eventfilter in my custom QTableWidget class like this:
bool custom_DropTable::eventFilter(QObject *obj, QEvent *evt)
{
if (evt->type() == QEvent::KeyPress)
{
QKeyEvent *keyEvent = static_cast<QKeyEvent *>(evt);
if (keyEvent->key() == Qt::Key_Return)
{
emit si_itemTextEntered(this->currentItem());
return true;
}
else
{
return false;
}
}
else
{
return QObject::eventFilter(obj, evt);
}
}
But the signal is never really arrived even if pressed enter so set the text.
Has someone any suggestions or improvements for me?
Upvotes: 3
Views: 6708
Reputation: 1935
You can make your widget no to send signals using QObject::blockSignals
. This way you can use the signal QTableWidget::itemChanged(QTableWidgetItem* item)
connected to an slot that will first block the signals of the table, then change the item, and then unblock the signals. Here you have a minimum example:
#include <QApplication>
#include <QTableWidget>
#include <QTableWidgetItem>
// Declare table globaly so the slot can block its signals
QTableWidget* table;
// Slot
void itemChanged(QTableWidgetItem* item)
{
// Block table signals
table->blockSignals(true);
// Change item background color
item->setBackgroundColor(Qt::red);
// Append text
item->setText(item->text() + " edited");
// Unblock signals
table->blockSignals(false);
}
int main(int argc, char** argv)
{
// Create application
QApplication app(argc, argv);
// Create table
table = new QTableWidget(3, 4);
// Add items
for (int i = 0; i < table->rowCount() * table->columnCount(); i++)
{
int row = i / table->columnCount();
int col = i % table->columnCount();
table->setItem(row, col, new QTableWidgetItem(QString::number(i)));
}
// Connect
QObject::connect(table, &QTableWidget::itemChanged, itemChanged);
// Show table
table->show();
// Run
return app.exec();
}
Upvotes: 4