c++ - 为什么在 qtablewidget 的第一列中设置值时 gui 崩溃

标签 c++ qt qt5

我的 UI 中有 QTableWidget。第一列是一组 QRadioButton。这是它的样子: enter image description here

我已将以下代码添加到 MainWindow 构造函数中:

for (char i = 0; i < ui->currentSetting1TableWidget->rowCount(); i++)
      ui->currentSetting1TableWidget->setCellWidget(i, 0, new QRadioButton(ui->currentSetting1TableWidget));

我还添加了以下代码:

void MainWindow::on_currentSetting1TableWidget_clicked(const QModelIndex &index)
{
    QRadioButton *b = (QRadioButton *)ui->currentSetting1TableWidget->cellWidget(index.row(), 1);
    b->setChecked(true);
}

我的代码在执行 b->setChecked(true); 时崩溃了。我认为这与我没有正确理解 C++ 中的转换以及 Qt 中的 cellWidget 返回的内容有关。我试图调查它,但我看不出问题是什么。如果能提供任何帮助,我将不胜感激。

最佳答案

使用 qobject_cast/dynamic_cast 用于转换从 QObject 派生的类型并检查返回值。

您似乎在第 0 列中设置单元格小部件,但您正在从第 1 列访问它。它很可能会立即返回 nullptr,查看您的屏幕截图。

关于c++ - 为什么在 qtablewidget 的第一列中设置值时 gui 崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39881429/

相关文章:

c++ - 结构中的数组

c++ - Armadillo 稀疏实矩阵与复 vector 的乘法

c++ - boost shared_ptr 的 const 正确性

c++ - 如何禁用或隐藏 QFileDialog 中的默认取消按钮?

Qt 5 与 SQLite : bindValue() results in "Parameter count mismatch" error

c++ - 使用带有继承的 Qt5 新连接语法

Android - native 全局对象析构函数从未被调用

c++ - 是否可以在 Qt 的顶级窗口之间使用相同的 OpenGL 上下文?

c++ - "There' s 没有为平台 Win32 分配给此项目的 Qt 版本"- Qt 的 Visual Studio 插件

perl - 选择一个 Perl GUI 模块以获得最大的跨平台使用率