我有一个 QTableWidget,在不同的列有不同类型的单元格小部件,有多个列显示复选框。
我想将 QCheckBox 的 stateChanged 信号连接到我的插槽之一,以便我可以在我的模型中相应地设置数据。
问题是当用户改变QCheckBox状态时,QTableWidget的当前行不一定改变。
所以我正在考虑继承QCheckBox并添加变量来保存行和列信息。这是一个好方法吗?当我使用 UI 元素存储数据时出现什么问题(如果有)。
最佳答案
我不会创建额外的类,而是将小部件的行和列存储在 map 中:
class YourWidgetWithTable
{
public:
void foo()
{
//when you add cell widgets, do something like this:
QCheckBox * b = new QCheckBox();
tableWidget->setCellWidget(row, col, b);
_widgetCells[b] = QPoint(row, col);
connect(b, &QCheckBox::stateChanged, this, &YourWidgetWithTable::checkboxStateChanged);
//if for whatever reason you are removing a checkbox from the table, don't forget to remove it from the map as well.
}
public slots:
void checkboxStateChanged(int)
{
//in your slot, you can now get the row and col like so:
QCheckBox * box = dynamic_cast<QCheckBox*>(sender());
QPoint rowAndColumn = _widgetCells[box];
}
private:
QMap<QCheckBox*, QPoint> _widgetCells; //QPoint for storing the row and column
}
当然,您可以在没有 dynamic_cast
的情况下使用 QObject*
指针来执行相同的操作。
关于c++ - 获取 QCheckBox 在 QTableWidget 中的单元格位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32218392/