QCombobox
-
Hi,
I'm trying to add the new word created by the user in the combobox to a file using on_comboBox_editTextChanged.
The code:#include "mainwindow.h" #include "ui_mainwindow.h" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); ui->comboBox->setMaxVisibleItems (8); ui->comboBox->setEditable (true); QFile inputFile("C:/Programming/Projects/Qcombobox2/combo.txt"); if(inputFile.open (QIODevice::ReadOnly | QIODevice::Text)) { QTextStream in(&inputFile); while(!in.atEnd ()) { QString line = in.readLine (); ui->comboBox->addItem (line); } } } MainWindow::~MainWindow() { delete ui; } void MainWindow::on_comboBox_editTextChanged(const QString String) { String == ui->comboBox->currentText (); QFile file("C:/Programming/Projects/Qcombobox2/combo.txt"); if(file.open (QIODevice::WriteOnly | QIODevice::Text |QIODevice::Append)) { QTextStream stream(&file); stream << String <<"\n"; stream.flush (); file.close (); } }
The result in the text file:
P
Ph
Pho
Phon
Phone
What am I doing wrong? Should I be using a different signal? (The goal is to add the word to the file before the submit button is clicked).
Thank you for your help. -
Hi,
You have several signals from QLineEdit, especially editingFinished:
http://doc.qt.io/qt-5/qlineedit.html#signals -
Judging by the name of your function you connected it to the 'currentTextChanged' signal. It's emitted whenever current text changes, i.e. on every key stroke.
If you are interested only in the final result you should override thefocusOutEvent
andkeyReleaseEvent
and watch for Enter/Return presses.
Alternatively you can calllineEdit()
on the combo to get the QLineEdit used and connect to its editingFinished() signal to get the same behavior.Btw. when passing strings as function params use
const QString& value
instead ofconst QString value
. It saves you from making an unnecessary copy. -
@gabor53 First get the QLineEdit instance of your QComboBox calling ui->comboBox->lineEdit().
Then connect the editingFinished() signal of that QLineEdit with a slot. In the slot you can call ui->comboBox->lineEdit()->text() to get the string.