我的问题是我希望数据库数据加上QComboBox中的默认值。当我使用 QStringList通过每次调用函数我都有重复项。这是updateComboBox函数:
void MainWindow::updCombo(){
QSqlQuery * qry1 = new QSqlQuery(mydb);
qry1->prepare("select DISTINCT Grp from Poems");
qry1->exec();
QStringList strList;
while(qry1->next()) {
if(!strList.contains(qry1->value(0).toString()))
{
qDebug()<< qry1->value(0).toString();
strList->append(qry1->value(0).toString());
}
}
ui->comboBox->addItems(strList);
}
答案 0 :(得分:0)
如果要向模型添加元素,可以使用代理,如下所示:
appendproxymodel.h
#ifndef APPENDPROXYMODEL_H
#define APPENDPROXYMODEL_H
#include <QIdentityProxyModel>
class AppendProxyModel: public QIdentityProxyModel{
public:
using QIdentityProxyModel::QIdentityProxyModel;
QVariant data(const QModelIndex &index, int role) const;
int rowCount(const QModelIndex &parent=QModelIndex()) const;
QModelIndex index(int row, int column, const QModelIndex &parent) const;
QStringList defaults() const;
void setDefaults(const QStringList &defaults);
private:
QStringList mDefaults;
};
#endif // APPENDPROXYMODEL_H
appendproxymodel.cpp
#include "appendproxymodel.h"
QVariant AppendProxyModel::data(const QModelIndex &index, int role) const
{
if(index.row() >= 0 && index.row() < mDefaults.size() && role==Qt::DisplayRole){
return mDefaults[index.row()];
}
if(index.row() >= mDefaults.size() && index.row() < rowCount()){
return QIdentityProxyModel::data(
QIdentityProxyModel::index(index.row()-mDefaults.size(), index.column()),
role);
}
return QIdentityProxyModel::data(index, role);
}
int AppendProxyModel::rowCount(const QModelIndex &parent) const
{
return mDefaults.size()+ QIdentityProxyModel::rowCount(parent);
}
QModelIndex AppendProxyModel::index(int row, int column, const QModelIndex &parent) const
{
if(row < rowCount()- mDefaults.size())
QIdentityProxyModel::index(row, column, parent);
return createIndex(row, column);
}
QStringList AppendProxyModel::defaults() const
{
return mDefaults;
}
void AppendProxyModel::setDefaults(const QStringList &defaults)
{
mDefaults = defaults;
emit dataChanged(index(0, 0, QModelIndex()), index(rowCount(),columnCount(), QModelIndex()));
}
示例:
QComboBox combo;
QSqlQueryModel model;
model.setQuery("select DISTINCT firstname from person");
AppendProxyModel proxy;
proxy.setDefaults({"all", "option1", "option2"});
proxy.setSourceModel(&model);
combo.setModel(&proxy);
下面的link中有一个完整的示例