0

我用QCheckBoxQTableWidgetCell

QWidget *widget = new QWidget();
QCheckBox *checkBox = new QCheckBox();
QHBoxLayout *layout = new QHBoxLayout(widget);
layout->addWidget(checkBox);
layout->setAlignment(Qt::AlignCenter);
layout->setContentsMargins(0, 0, 0, 0);
widget->setLayout(layout);
table->setCellWidget(0, 0, widget);

我不能得到这个QCheckBox

QTableWidgetItem *item     = ui->table->item(0, 0);

QWidget          *widget   = dynamic_cast<QWidget *>(item); // Widget==0

QHBoxLayout      *layout   = dynamic_cast<QHBoxLayout *>(widget->layout());
QCheckBox        *checkBox = dynamic_cast<QCheckBox *>(layout->widget());
4

3 回答 3

2

我认为您需要执行以下操作:

QCheckBox *chkBox = qobject_cast<QCheckBox*>(_ui->tableBonus1Lines->cellWidget(0, 0));
于 2014-10-09T14:57:48.687 回答
1

如果您使用类似的东西创建了一个小部件:

QWidget* createCheckBoxWidget(bool checked)
{
    QWidget* pWidget = new QWidget();
    QCheckBox* pCheckBox = new QCheckBox();
    pCheckBox->setChecked(checked);

    QHBoxLayout* pLayout = new QHBoxLayout(pWidget);
    pLayout->addWidget(pCheckBox);
    pLayout->setAlignment(Qt::AlignCenter);
    pLayout->setContentsMargins(0,0,0,0);
    pWidget->setLayout(pLayout);

    return pWidget;
}

然后将其添加到 QTableWidget 中,如下所示:

QTableWidget* tableWidget = new QTableWidget();
tableWidget->setRowCount(1);
tableWidget->setColumnCount(1);

QWidget* checkBox = createCheckBoxWidget(true);
tableWidget->setCellWidget(0, 0, checkBox);

您可以使用以下函数检索它:

QCheckBox* getCheckBoxWidgetFromCell(QTableWidget* table, int row, int col)
{
    QCheckBox* checkBox = nullptr;

    if (QWidget* w = table->cellWidget(row, col))
    {
        if (QLayout* layout = w->layout())
        {
            if (QLayoutItem* layoutItem = layout->itemAt(0))
            {
                if (QWidgetItem* widgetItem = dynamic_cast<QWidgetItem*>(layoutItem))
                {
                    checkBox = qobject_cast<QCheckBox*>(widgetItem->widget());
                }
            }
        }
    }

    return checkBox;
}

并像这样访问它的状态:

QCheckBox* checkBox = getCheckBoxWidgetFromCell(tableWidget, 0, 0);
if (checkBox)
{
    bool checked = checkBox->isChecked();
}

因此,了解您插入到表格单元格中的对象的层次结构非常重要。

此处的布局是可选的,但您可以控制小部件在单元格内的显示方式。它还表明,一个单元格可以根据需要包含非常复杂的小部件或小部件组。

于 2019-08-16T21:52:25.293 回答
1

You can get CheckBox with center alignment at help this code:

try {
    QWidget *mainWidget = qobject_cast<QWidget *>(pTableWidget->cellWidget(row, column);
    QHBoxLayout *hBoxLayout = qobject_cast<QHBoxLayout *>(mainWidget->layout());
    QLayoutItem *item = hBoxLayout->layout()->takeAt(0);
    QWidget* widget = item->widget();
    QCheckBox *chechBox = qobject_cast<QCheckBox *>(widget);
    return chechBox;
} catch (...) {
    return NULL;
}
于 2016-03-29T07:14:34.053 回答