How to properly add strings to QListWidgets?

懵懂的女人 提交于 2019-12-24 05:16:13

问题


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();
    }
}

回答1:


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!




回答2:


To get a QStringList from a std::vector<std::string>, you'll need to use QString::fromStdString on all the elements. For example:

#include <QStringList>

#include <algorithm>
#include <string>
#include <vector>

QStringList convert(const std::vector<std::string>& v)
{
    using std::begin;
    using std::end;
    QStringList l;
    l.reserve(v.size());
    std::transform(begin(v), end(v), std::back_inserter(l),
                   &QString::fromStdString);
    return l;
}

Then you can populate a QStringListModel feeding a QListView, as suggested in other answer.



来源:https://stackoverflow.com/questions/32084336/how-to-properly-add-strings-to-qlistwidgets

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!