when developing qt, QStringList should be display on ‘ui->listView’, However, following code won’t work.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ... QDir myDir("C:\\"); QStringList filter("*"); QStringListModel model; QStringList filesList = myDir.entryList(QStringList(filter),QDir::Files | QDir::Dirs); model.setStringList(filesList); ui->listView->setModel(&model); ... } |
because ‘model’ object will be delete after function is done.
ui->listView will not be able to get model object.
move to MainWindow ‘model’ to MainWindow declare will be good.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | class MainWindow : public QMainWindow { Q_OBJECT public: explicit MainWindow(QWidget *parent = 0); ~MainWindow(); QStringListModel model; private: Ui::MainWindow *ui; }; MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ... QDir myDir("C:\\"); QStringList filter("*"); QStringList filesList = myDir.entryList(QStringList(filter),QDir::Files | QDir::Dirs); model.setStringList(filesList); ui->listView->setModel(&model); ... } |