Search code examples
c++qtqcompleter

QCompleter - how to import data from file


I am quite new to Qt. I tried to find answers here but did not succeed so far. I have in a main.cpp file a vector of a complex struct and I would like to use it as an input for the QCompleter I have defined in a void function of my mainwindow.cpp that creates among other thing a QLineEdit to which I associate this QCompleter. How shall I transfer this vector to my completer ? Part of main.cpp:

//... l is a vector based on a struct containing, among other thing , string name.
QApplication a(argc, argv);
QStringList *LocationStringList=new QStringList;
for (int k=0;k!=l.size();k++)   {
    LocationStringList->append(QString::fromStdString(l[k].name));
}
MainWindow w;
w.show();

part of MainWindows.cpp :

void MainWindow::new()
{
    ...
    QCompleter *cmpt;
    cmpt=new QCompleter(LocationStringList,this);
    cmpt->setCaseSensitivity(Qt::CaseInsensitive);
    QLineEdit *locationLineEdit = new QLineEdit();
    locationLineEdit->setCompleter(cmpt);
    ...

It seems it does not know : LocationStringList


Solution

  • What have you tried? Normally, you can use it like this:

    QStringList list;
    for(auto& complexStructObject : complexStructList)
        list << complexStructObject.getStringForCompletion();
    
    QCompleter* myCompleter = new QCompleter(list, this);
    
    myLineEdit->setCompleter(myCompleter);
    

    In your example, I would pass the list to your class:

    // main.cpp
    
    // above keeps unchanged
    MainWindow w(LocationStringList);
    w.show();
    // at the end, do not forget to delete!! your string list is not managed; better yet use a unique_ptr
    
    // MainWindow.h
    #include <QStringList>
    
    class MainWindow
    {
    Q_OBJECT
    public:
        MainWindow(QStringList* stringList);
    
        // ...
    };
    
    // MainWindows.cpp
    MainWindow::MainWindow(QStringList* stringList)
    {
        QCompleter *cmpt;
        cmpt=new QCompleter(*stringList, this);
        cmpt->setCaseSensitivity(Qt::CaseInsensitive);
        QLineEdit *locationLineEdit = new QLineEdit();
        locationLineEdit->setCompleter(cmpt);
    }
    

    new is a reserved keyword, so you should probably just use your constructor