Frage

I am trying to create a new row in a QTableWidget on an itemChanged signal. Here is the code:

Constructor::
{
ui->tblRoles->insertRow(0);
QTableWidgetItem *twl = new QTableWidgetItem("New Role");
QFont f = twl->font();
f.setItalic(true);
twl->setFont(f);
twl->setForeground(Qt::gray);
ui->tblRoles->setItem(0, 0, twl);

QObject::connect(ui->tblRoles, SIGNAL(itemChanged(QTableWidgetItem*)), 
    this, SLOT(newRole(QTableWidgetItem*)));
}

This above creates an initial row for the table and connects the signal to the slot. The slot below checks if this is the correct cell that was changed, and if yes updates it, and creates a new row... At least it should do this:

void RoleListingForm::newRole(QTableWidgetItem *itm)
{

if(itm->row() == 0 && itm->column() == 0)
{
    QFont f = itm->font();
    f.setItalic(false);
    itm->setFont(f);
    itm->setForeground(Qt::black);


    ui->tblRoles->blockSignals(true);    //////
    ui->tblRoles->insertRow(0);
    QTableWidgetItem *twl = new QTableWidgetItem("New Role");
    f = twl->font();
    f.setItalic(true);
    twl->setFont(f);
    twl->setForeground(Qt::gray);
    ui->tblRoles->setItem(0, 0, twl);
    ui->tblRoles->blockSignals(false); ///// 
}
}

If I remove the blockSignals(), the code enters an infinite loop, and if I leave the blockSignals() it creates a random number of rows, usually three ...

Any idea How to make this work?

Background info: I am trying to implement this: https://ux.stackexchange.com/questions/33331/about-the-creation-and-management-of-items

Thanks a lot

War es hilfreich?

Lösung

So after some research, the reason for this funny behaviour is more or less self evident after reading the documentation:

void QTableWidget::itemChanged ( QTableWidgetItem * item ) [signal]

This signal is emitted whenever the data of item has changed.

What is happening is the following:

I call:

itm->setFont(f);
itm->setForeground(Qt::black);

but both of these are translated to "data" changes by Qt, and since I block the signals after these two calls, obviously I get 2 extra rows.

So, put the blockSignals before the font/color changes and it works.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top