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