Search code examples
c++qtiteratorqhash

QMutableHashIterator - no appropriate default constructor


I am trying to pass data into my hash named "dictionary", I thought I would use a QMutableHashIterator to iterate through the hash and add values to it, however, I keep on getting this error but I have no idea how to solve it. I have looked at other questions with a similar error but none of them really helped me. So I thought I would ask, can someone please help me solve this error:

mainwindow.cpp:7: error: C2512: 'QMutableHashIterator<QString,QString>' : no appropriate default constructor available

Here is my code:

mainwindow.h:

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include <QMessageBox>

namespace Ui {
  class MainWindow;
}

class MainWindow : public QMainWindow
{
  Q_OBJECT

public:
  explicit MainWindow(QWidget *parent = 0);
  ~MainWindow();

private slots:
  void on_pushButton_clicked();

private:
  Ui::MainWindow *ui;
  QHash<QString, QString> dictionary;
  QMutableHashIterator<QString, QString> i;
};

mainwindow.cpp:

#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
  ui->setupUi(this);

  const QString content = "word";
  i = dictionary;
  while(i.hasNext())
  {
    i.next();
    i.setValue(content);
  }
}

MainWindow::~MainWindow()
{
  delete ui;
}

void MainWindow::on_pushButton_clicked()
{
  QString word = "dog";

  while(i.findNext(word))
  {
    QMessageBox::information(this,tr("Word Has Been found"),
                             word);
  }
}

Thanks in advance!


Solution

  • You have to initialise i with the QHash you want to traverse. See QMutableHashIterator documentation.

    MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow),
    i(dictionary) // here
    {
      // ...
    }
    

    Or simply, if your solution's logic allows to, create the iterator each time you want to use it instead as a member variable.