QTextStream crashing program when adding items to combobox



  • Hi,
    I use QTextStream to populate a combobox:

            QFile inputFile("C:/Programming/Projects/Folkfriends/combo.txt");
    
            if(inputFile.open (QIODevice::ReadOnly | QIODevice::Text))
            {
                QTextStream in(&inputFile);
                while(!in.atEnd ())
                {
                    QString Material = in.readLine ();
                    Material_Combo->addItem (Material)	;
                }
            }
    

    Any idea why the while loop crashes the program? (It gives a message like "Stopped working)?

    Thank you.



  • For me it seems valid, but if i were you I would try peeking what exactly in.readLine() is returning every time (mayby the file is corrupted?).

    QDebug() << "Read string: " <<  Material;
    

  • Lifetime Qt Champion

    Hi,

    Maybe a silly question but, did you initialize Material_Combo correctly ?



  • Hi,
    I initialized like this:

    QComboBox *Material_Combo = new QComboBox;
    

    I checked what in.readLine() returns and found this:

    Read Matarial string: "Wood"
    Read Matarial string: "Metal"
    Read Matarial string: ""
    Read Matarial string: ""
    Read Matarial string: ""
    Read Matarial string: ""
    Read Matarial string: ""
    Read Matarial string: ""
    Read Matarial string: ""
    Read Matarial string: ""

    The empty strings are keep going until I terminate the program. There are 2 lines in the txt file, Wood and Metal. I think it can't find the end of the file maybe, but I don't know why. Thank you for any ideas.



  • I think it is the while loop. I added this section to the program line by line and the only time, when the program crashed is when I added the while loop. Still don't know though why it crashes.



  • If I take away the ! sign and just use

    while(in.atEnd())
    

    the program does not crash though the loop reads nothing. Still don't kn ow why....



  • Mayby try this one:

    QComboBox *Material_Combo = new QComboBox(this);
    do
    {
        QString line = in.readLine();
        QDebug() << "line: " << line;
        Material_Combo->addItem(line);
    } while (!line.isNull());
    

    It is the same but diffrent... Still the same :D I mean i dont know why it crashes when you use atEnd()however it seems that the file is corrupted since the end of file is not detected (file encoding thing possible..?).


  • Lifetime Qt Champion

    Or, since it's a text file:

    QFile inputFile("C:/Programming/Projects/Folkfriends/combo.txt");
    if (!inputFile.open(QIODevice::ReadOnly | QIODevice::Text))
         return;
    
    while (!inputFile.atEnd()) {
        QByteArray material = inputFile.readLine();
        Material_Combo->addItem (material)  ;
    }
    

    ?


Log in to reply
 

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