Search code examples
c++qtqlistwidgetqlistwidgetitem

How to properly add strings to QListWidgets?


In the following code the method exec(const char *cmd) runs a bash script and returns the output as a vector of strings. The intent is to create a QListWidgetItem out of each of those strings and add them to a QListWidget on a little GUI that I have created, but the QListWidgetItems are not created successfully. I always seem to be required to use a const char* to create either a QString or QListWidgetItem, it will not allow me to create one using a string variable.

You can see what I am going for in the line: QString nextLine = txtVcr.back(); There is an exception thrown here, it wants QString set to a const char*, for example QString nextLine = "Hello, World!";

How do I go about getting the strings from my vector and creating QListWidgetItems out of them to add to my QListWidget?

In C# everything was rather direct in that I could add strings or whatever else to any container/widget. Is there an intermediate step that I am overlooking with these "QWidgets"? Perhaps I should be casting to "Q" types?

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

    vector<string> exec(const char *cmd);
    vector<string> txtVcr = exec("/home/rhurac/getServices.sh");

    while (!txtVcr.empty())
    {
        QString nextLine = txtVcr.back();
        ui->uxListWidget->addItem(new QListWidgetItem(nextLine, ui->uxListWidget));
        txtVcr.pop_back();
    }
}

Solution

  • Simply don't use QListWidgets and other QxyzWidget classes. They are depricated, and left in Qt for compatibility with old code (Qt3 basically).

    Use QListView and QStringListModel for your use-case. E.g.

    QListView *lv = new QListView();
    QStringListModel m;
    QStringList data = QStringList()<<"AAA"<<"BBB"<<"CCC";
    m.setStringList(data);
    lv->setModel(&m);
    lv->show();
    

    P.S.: Sorry, it doesn't answer your question directly. But unless you have to support legacy code, don't touch QListWidgets!