Creating a simple form using C++/Wt (Witty)
In this entry I’m going to create a simple form. This form will show you how to use controls and events in a very simple way.
A couple things you have to notice before we start:
- I’m going to inherit from WContainerWidget. As you now know, I could have inherited from WApplication too.
- Most controls like, WLabel, WLineEdit and WPushButton include a “parent” parameter in their constructors. But you can also create them and add them later to any WContainerWidget. I’m doing this to our text control. To add it to a container you have to call the WContainerWidget::addWidget method.
- The code is based on our previous Hello World application. There are few lines that changed.
So, here it is:
#include <Wt/WApplication>
#include <Wt/WContainerwidget>
#include <Wt/WLabel>
#include <Wt/WLineEdit>
#include <Wt/WPushButton>
#include <Wt/WText>
using namespace Wt;
class FormExample: public WContainerWidget {
private:
WLabel* label;
WLineEdit* edit;
WPushButton* button;
WText* text;
public:
FormExample(WContainerWidget *parent = 0): WContainerWidget(parent) {
label = new WLabel(this);
edit = new WLineEdit(this);
button = new WPushButton(this);
text = new WText();
addWidget(text);
label->setText("What is your name? ");
button->setText("Send");
button->clicked().connect(this, &FormExample::buttonClicked);
}
void buttonClicked() {
text->setText("Hello " + edit->text());
}
};
WApplication* createApplication(const WEnvironment &env) {
WApplication* app = new WApplication(env);
app->setTitle("Form Test");
app->root()->addWidget(new FormExample());
return app;
}
int main(int argc, char** argv) {
return WRun(argc, argv, &createApplication);
}
You should see something like this:
Happy coding.