c++ - 获取从 QTableWidget 中的单元格小部件发出的信号发送器的行索引

标签 c++ qt signals-slots

我有一个包含 3 列的 QTableWidget。 前两列存储一个 QDateTimeEdit 项目。 第三个存储一个 QSpinBox,它应该列出该行中两个 QDateTimeEdit 值之间的持续时间。

如何连接 QDateTimeEdit 的信号以在日期时间更改时自动更新 QSpinBox 中的持续时间?

...
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()));
}

插槽:

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
}

我想这在某种程度上可以通过使用 ->parent() 函数实现?

最佳答案

假设您使用的是 Qt5,那么您可以使用 lambda。所以像(未经测试的)...

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);
}

关于c++ - 获取从 QTableWidget 中的单元格小部件发出的信号发送器的行索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58076265/

相关文章:

c++ - 如何将Qt中的keyPressEvent传递给基类?

python - PySide(或 PyQt)信号和槽基础知识

c++ - 准确计算编译器在结构中添加的填充

c++ - Visual C++ 中的 "No appropriate default constructor available"错误

c++ - 在 C++ 程序中使用 C 库中定义的类型,命名空间类似于方案

c++ - QTreeView - 排序和过滤模型

c++ - 制作一个优化未使用部分的元组样式类

c++ - QT 4 <->QT 5 编码

c++ - Qt Version 5.3 将数据从一个论坛发送到另一个

c++ - 无法连接(空)::selectionChanged 到 QTableView