c++qtqstringqtwidgetsqstringlist

How to get multiple strings from input and store them in QStringList?


I'm using Qt framework to create an employee interface, which stores information of an employee (ID, name, surname, skills, etc..)

In the widget interface I've used a lineEdit for everything, since I need to store string types of information, the only exception is skills parameter, that should be a list of strings.

In my mainwindow.cpp, I should store a list of different skills, not just one, and that's the error I'm getting when I use my function addEmployee(), because it needs a list of strings (skills), not one string.

I should use QStringList skills, but how do I tell if the user is inserting multiple skills , and how do I store that single output in a list?

void MainWindow::on_add_pushButton_clicked()
{
    QString id = ui->id_lineEdit->text();
    QString nome = ui->name_lineEdit->text();
    QString cognome = ui->surname_lineEdit->text();

    QString skills = ui->skills_lineEdit->text();
    //should be QStringList skills 
    //but how can I tell the user is inserting different skills? 

    manage.addEmployee(id.toStdString(),
                       name.toStdString(),
                       surname.toStdString(),
                       skills.toStdString());

    //'manage' refers to the class manageEmployee.h
    //I already implemented to use function addEmployee(id, name, surname, {skills});
}

Solution

  • The question is a bit unrefined, but I will try my best to answer based on what I could follow.

    void MainWindow::on_add_pushButton_clicked()
    {
        QString id = ui->id_lineEdit->text();
        QString name = ui->name_lineEdit->text();
        QString surname = ui->surname_lineEdit->text();
    
        QString skills = ui->skills_lineEdit->text();
        QStringList skillsList = skills.split(","); // or ";", etc.
    
        std::list<std::string> skillsStdList;
        for (const QString& qstr : skillsList) {
            skillsStdList.push_back(qstr.toStdString());
        }
    
        manage.addEmployee(id.toStdString(), name.toStdString(), surname.toStdString(), skillsStdList);
    }
    

    So if you want the user to input list of skills, you wanna be splitting them using a delimiter as well. Then you can pass the resulting QStringList to .addEmployee assuming it takes a fourth argument std::list<std::string>

    By using a delimiter, you allow the user to enter multiple skills as a single input, which simplifies the interface. However, you should make sure to handle any errors that can arise from invalid input, such as an empty or malformed input string.

    Edit: Code updated in mind with QList<Qstring> not supporting toStdString method