Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

QTableWidget->setItem triggers on_tableWidget_itemChanged slot



  • Hi,
    I have a table and I want to make sure that user input is a hex number. I am checking entered text in on_tableWidget_itemChanged() slot, if it is not hex I set the cell with default value "00000000", but this setting triggers second on_tableWidget_itemChanged slot which I don't want. How can I avoid second call of on_tableWidget_itemChanged slot?

    Or how can I restrict user inputs only for Hex values?

    void MainWindow::on_tableWidgetRegisterList_itemChanged(QTableWidgetItem *writeItem)
    {
        if(TableInit && writeItem->column() == 4) // write column
        {
            bool convertState;
            QTableWidgetItem *nameItem = ui->tableWidgetRegisterList->item(writeItem->row(), 0); // name column
            QString regName = nameItem->text();
            quint32 regWriteVal = writeItem->text().toUInt(&convertState, 16);
            int i = 0;
    
            if(!convertState)  // User input is not hex
            {
                regWriteVal = 0;
                QTableWidgetItem *defaultItem = new QTableWidgetItem;
                defaultItem->setText("00000000");
                defaultItem->setBackground(nameItem->background().color());
                ui->tableWidgetRegisterList->setItem(writeItem->row(), writeItem->column(), defaultItem);  //If user input is not hex, this slot will be recalled again because of this function setItem()
            }
            else
                for(i = 0; i < Registers.size(); i++)
                {
                    if(Registers[i].Name.compare(regName.split('.')[0]) == 0)
                    {
                        Registers[i].Write = regWriteVal;
                        Registers[i].ToSend = convertState;
                        writeItem->setBackground(Qt::yellow);
                        break;
                    }
                }
        }
    }
    

  • Lifetime Qt Champion

    Hi,

    Why not do that at the editor level ? Using e.g. a QStyledItemDelegate. Doing so would avoid user entering anything that's incorrect.


Log in to reply