Populating a QcomboBox using lines from a file



  • I need to populate a QcomboBox from a text file using the following code:

    #include "dialog.h"
    #include "ui_dialog.h"
    #include <QtCore>
    #include <QtGui>
    #include <QMessageBox>
    #include <QCompleter>
    #include <QTextStream>
    #include <QComboBox>

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

    ui->comboBox->setMaxVisibleItems (8);
    ui->comboBox->setEditable (true);
    
    QFile file("C:/Programming/widget/QCombobox/combo.txt");
    QTextStream stream(&file);
    QString line;
    
    if(file.open (QIODevice::ReadOnly | QIODevice::Text))
    {
    	if(!line.isNull ())
        {
    		line = stream.readLine ();
            ui->comboBox->addItem (line);
        }
    
        stream.flush ();
        file.close ();
    }
    

    }

    After running it, nothing happens. Please help me to find out what is wrong with it.
    Thank you.


  • Moderators

    The readline is never executed. Change

        if(!line.isNull ())
        {
            line = stream.readLine ();
            ui->comboBox->addItem (line);
        }
    

    to

        line = stream.readLine ();
        if(!line.isNull ())
        {
            ui->comboBox->addItem (line);
        }
    

  • Qt Champions 2016

    hi
    Well you read only first line (after @koahnig fix)

    QFile inputFile(fileName);
    if (inputFile.open(QIODevice::ReadOnly))
    {
      QTextStream in(&inputFile);
      while (!in.atEnd())
      {
         QString line = in.readLine();
        ui->comboBox->addItem (line);
      }
      inputFile.close();
    }
    

  • Moderators

    @mrjj
    Sorry, to object, but even the first line is not read.
    However, your source looks certainly better for adding a couple of lines than mine. ;)


  • Qt Champions 2016

    @koahnig
    yeah I edited after I saw you post. I totally missed that not even first will be read :)



  • Thank you it worked.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.