【问题标题】:QTableView check if the String already existsQTableView 检查字符串是否已经存在
【发布时间】:2014-08-07 09:20:05
【问题描述】:

我有一个程序可以将字符串放入带有模型/视图的 TableView 中。 我的模型来自 QAbstractTableModel,我的视图来自 QTableView。 它在我的模型setData()中按名称排序:

beginInsertRows(QModelIndex(), names.size(), names.size());
names.push_back(name);
values.push_back(value);
endInsertRows();

现在我会检查我要添加的字符串是否已经存在于我的表中,当它存在时我不会添加它。 我可以使用QTableWidget 制作it 吗:

QList<QTableWidgetItem *> ItemList = table->findItems(strname, Qt::MatchExactly);
if ( ItemList.count() == false )
{/*add*/}
else {/*QMessageBox */}

但我不知道 QTableView。 我该怎么办 ?

然后我的表中总是有复选框,但我从未添加它们。 当我添加 1 时,它会使复选框自动变为蓝色。

这是方法的链接,非常奇怪:View::PushButtonClicked

【问题讨论】:

  • 现在我的程序做的很奇怪。当我添加“1”和“1”时,我添加“1”和“1”并推入我的 msgBox“保存”它保存,但我添加“Hallo”“Du”。它说它已经存在并且例如它清除表。 [这里是方法][1] [1]:pastebin.com/3uieTWPh

标签: c++ qt qtableview model-view qabstracttablemodel


【解决方案1】:

我想您有一个 QAbstractItemModel(或 QAbstractTableModel)的子类,您可以从中获取数据。 您可以检查调用您的实现的模型中的字符串搜索

QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const;

或者您可以在该成员返回 QVariant 的源中进行搜索;

或者你可以使用

QModelIndexList QAbstractItemModel::match ( const QModelIndex & start, int role, const QVariant & value, int hits = 1, Qt::MatchFlags flags = Qt::MatchFlags( Qt::MatchStartsWith | Qt::MatchWrap ) ) const

【讨论】:

    【解决方案2】:

    对于表格视图,您可以使用QAbstractItemModel::match() 函数在其模型中搜索给定的文本。例如:

    QModelIndexList indexes = model->match(QModelIndex(), Qt::DisplayRole, "text");
    if (indexes.size() > 0) {
        // Add new item...
    }
    

    【讨论】:

      【解决方案3】:

      您可以使用QSortFilterProxyModel 在您的模型中搜索:

      QSortFilterProxyModel proxy;
      proxy.setSourceModel(myTableModel);
      proxy.setFilterFixedString(searchString);
      
      QModelIndex matchingIndex = proxy.mapToSource(proxy.index(0,0))
      
       if(matchingIndex.isValid())
       {
           QMessageBox::information(this, "Find", "Found");
       }
       else
       {
           QMessageBox::information(this, "Find", "Not Found");
       }
      

      【讨论】:

      • 非常感谢!但我有 2 个字符串:名称和值。但我只会检查名称是否存在,而不是与值相同的字符串。当我关闭 msgBox 时,表格被清除了 o.o ?!例如,我添加名称:AName,值:AValue。比我添加:名称:AValue,值:BValue。应该添加。但它说字符串存在..
      猜你喜欢
      • 2021-11-10
      • 1970-01-01
      • 2012-02-14
      • 1970-01-01
      • 1970-01-01
      • 2012-05-13
      • 1970-01-01
      相关资源
      最近更新 更多