user7431005
user7431005

Reputation: 4547

get row index of signal sender emitted from cell widget in QTableWidget

I have a QTableWidget with 3 columns. The first two columns store a QDateTimeEdit item. The third stores a QSpinBox which should list the duration between the two QDateTimeEdit values in this row.

How can I connect a signal of the QDateTimeEdit to automatically update the duration in the QSpinBox in case one date-time is changed?

...
for (int i_row = 0; i_row < 100; ++i_row){
    QTableWidget *t = ui->tableWidget;
    QDateTimeEdit *start = new QDateTimeEdit();
    QDateTimeEdit *end   = new QDateTimeEdit();
    t->setCellWidget(i_row,0,start);
    t->setCellWidget(i_row,1,end);

    QSpinBox *sp = new QSpinBox();
    sp->setReadOnly(true);
    t->setCellWidget(i_row,2,sp);

    connect(start, SIGNAL(dateTimeChanged(const QDateTime &)), this, SLOT(adjustDuration()));
    connect(end,   SIGNAL(dateTimeChanged(const QDateTime &)), this, SLOT(adjustDuration()));
}

with the slot:

void mainWindow::adjustDuration()
{
    QDateTimeEdit *s = qobject_cast<QDateTimeEdit *>(sender());
    // How do I get row number of the sender within QTableWidget in order to be able to access proper 2nd QDateTimeEdit and QSpinBox? 
    // Simplified speaking: I would like to get the value i_row from the code before
}

I suppose it is somehow possible by using the ->parent() function?

Upvotes: 0

Views: 520

Answers (1)

G.M.
G.M.

Reputation: 12929

Assuming you're using Qt5 then you could make use of a lambda. So something like (untested)...

for (int i_row = 0; i_row < 100; ++i_row){
    QTableWidget *t = ui->tableWidget;
    QDateTimeEdit *start = new QDateTimeEdit();
    QDateTimeEdit *end   = new QDateTimeEdit();
    t->setCellWidget(i_row, 0, start);
    t->setCellWidget(i_row, 1, end);

    QSpinBox *sp = new QSpinBox();
    sp->setReadOnly(true);
    t->setCellWidget(i_row, 2, sp);

    auto eval = [start, end, sp]()
                {

                    /*
                     * Here you have 'start', 'end' and 'sp'.  Use them
                     * in whatever way you see fit.
                     */
                };

    connect(start, &QDateTimeEdit::dateTimeChanged, eval);
    connect(end,   &QDateTimeEdit::dateTimeChanged, eval);
}

Upvotes: 3

Related Questions