c++ - 我可以将模型中的 bool 转换为 QComboBox 中的是/否吗

标签 c++ qt

我有一个列值为 0/1 的数据库。

我使用 QSqlRelationalTableModel 向小部件显示数据。

是否可以在 QComoboBox 中对 1 显示 Yes,对 0 显示 No? 而且,当我选择是/否时,它应该作为 1/0 保存到数据库中。

我可以用 setData()getData() 函数做些什么吗?有人可以提供线索如何开始吗?

更新:

    mpCountryModel->setTable("CountryMaster");
    mpCountryModel->select();

    ui->comboBox->setModel(mpCountryModel);
    ui->comboBox->setModelColumn(5);

因为第5列有值0或1,同样会显示0和1,对吧?

最佳答案

这有什么好处吗?这对我有用。

TableModel* model = new TableModel(this);
ui->comboBox->setModel(model);
ui->comboBox->setModelColumn(TableModel::BoolColumn);

//------------ tablemodel.h --------------------

QVariant data(const QModelIndex& index, int role) const;

int columnCount(const QModelIndex& ) const
{
    return 2;
}

int rowCount(const QModelIndex& parentIndex) const
{
    return parentIndex.isValid() ? 0 : 2;
}

//-------------------- tablemodel.cpp ----------------

QVariant TableModel::data(const QModelIndex& index, int role) const
{
   if (!index.isValid() || index.row() > 2) {
      return QVariant();
   }

switch (role) {
    case Qt::DisplayRole:
    case Qt::EditRole:
        if (index.column() == 0)
            return tr("Column %1").arg(index.column());
        else
            if (index.row() % 2 == 0)
                return "Yes";
            else
                return "No";
    default:
        break;
}
return QVariant();
}

关于c++ - 我可以将模型中的 bool 转换为 QComboBox 中的是/否吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31995345/

相关文章:

c++ - 使用循环将多行写入 .txt

c++ - 在这种情况下如何使用 auto_ptr

c++ - 拔下以太网电缆和从操作系统禁用以太网网络之间的区别

c++ - Qbs,不存在的基本配置文件错误

c++ - QRegularExpression 源字符串中的匹配位置

c++ - 在输入单独的函数之前强制 Qt GUI 更新

C++简单的线程问题

c++ - 在 QLabel 上将 float 显示为 QString 显示 "G",其中点 "."应该去

C++ 端口扫描器

c++ - 如何从其方法中删除对象?