I’m trying to write a simple Qt program which takes text inside a QLineEdit and appends it into a QTextEdit object when the return key is pressed.
Here is the code for my program:
#include <QApplication>
#include <QtGui>
#define WIDTH 640
#define HEIGHT 480
int main(int argc, char* argv[])
{
QApplication app(argc, argv);
QTextEdit textArea;
textArea.setReadOnly(true);
QLineEdit lineEdit;
QPushButton quit("Quit");
QObject::connect(&quit, SIGNAL(clicked()), qApp, SLOT(quit()));
QHBoxLayout hLayout;
hLayout.addWidget(&lineEdit);
hLayout.addWidget(&quit);
QVBoxLayout vLayout;
vLayout.addWidget(&textArea);
vLayout.addLayout(&hLayout);
QWidget window;
window.setBaseSize(WIDTH, HEIGHT);
window.setLayout(&vLayout);
window.show();
//This is the line I can not get to work
QObject::connect(&lineEdit, SIGNAL(returnPressed()), &textArea, SLOT(append(lineEdit.text())));
return app.exec();
}
Essentially, the problem is connecting the QLineEdit returnPressed() SIGNAL to the QTextEdit append() SLOT. I am hoping someone can point out what is wrong with my code.
Thank you very much in advance for your time.
When you run your program, you should notice on the console the following Qt error output..
You would need to qualify the
appendreference in your call toconnectwith theQTextEditvariable nametextArea.But that’s not going to help much because you can only specify signal and slot method names and parameter types when calling
connectso you can’t specifylineEdit.text()in there.Since the
append()slot expects aQString, ideally you would want to connect a signal that includes aQStringbut there is no such signal forQLineEdits.You pretty much have to write a slot yourself that you can connect to
returnPressed()and calltextArea.append(lineEdit.text())from there. You will need to subclass aQObjectof some kind to write a slot which would usually mean subclassingQWidgetand putting all of your UI building code in its constructor.You might also notice that your program crashes when you close it. Since Qt likes to manage the destruction of most
QObjects itself, it is usually best to allocate allQObjectinstances on the heap withnew. This isn’t technically necessary all the time but it is much easier 🙂