c++ - 获取 QCheckBox 在 QTableWidget 中的单元格位置

标签 c++ qt

我有一个 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/

相关文章:

c++ - 迭代器删除 C++ 的自定义实现

c++ - 对维基百科的 HTTP 请求

c++ - 读取二进制文件中的字符串 C++

c++ - 控制台上的 Qt 应用程序文本流

c++ - 未初始化的变量被使用

c++ - 用于将 RGB 图像转换为灰度图像的共享内存 Cuda

c++ - Qt:使用 QPainter 渲染的垂直文本的抗锯齿

python - 在 Qt 5 中嵌入 Python

c++ - QTableView,选择并按住shift+点击

c++ - 如何让QtCreator中的应用程序使用KDE oxygen主题?