我在QCheckBox
QTableWidgetCell
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());
答案 0 :(得分:2)
我认为您需要执行以下操作:
QCheckBox *chkBox = qobject_cast<QCheckBox*>(_ui->tableBonus1Lines->cellWidget(0, 0));
答案 1 :(得分: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();
}
因此了解插入到表格单元格中的对象的层次结构很重要。
这里的布局是可选的,但确实可以控制窗口小部件在单元格中的显示方式。它还显示单元可以根据需要包含非常复杂的小部件或小部件组。
答案 2 :(得分:0)
您可以在帮助此代码时获得CheckBox
居中对齐:
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;
}