Search code examples
c++qtqtcoreqfileqtextstream

Qt Creator combobox


How to write Combobox current text in a preexisting text file in hard drive? Here is my code:

void second::on_pushButton_4_clicked()
    {
         QFile file("vik.txt");
         if (!file.open(QIODevice::WriteOnly | QIODevice::Text))
             return;
         QTextStream out(&file);
         out << ui->comboBox_5->currentText() << "\n";
}

Solution

  • Maybe you forgot to close the file

    void second::on_pushButton_4_clicked() 
    {
        // Get comboBox text value
        QString txt = ui->comboBox_5->currentText();
    
        // Open file for writing
        QFile file("vik.txt");
        file.open(QIODevice::WriteOnly | QIODevice::Text);
        QTextStream out(&file);
    
        // Write in file
        out << txt << "\n";
    
        // Close file
        file.close();
    }