In these next few examples let’s look at some of the properties for a QLineEdit. This example will show text justification.
#include <QtCore>
#include <QtGui>
class MainWindow : public QWidget
{
public:
MainWindow();
};
The declaration for MainWindow only needs a constructor for this example.
MainWindow::MainWindow()
{
setMinimumSize(700, 350);
// text edit
QLineEdit *text_1 = new QLineEdit();
text_1->setText("Sample text on the Left");
text_1->setMinimumSize(400, 35);
text_1->setAlignment(Qt::AlignLeft);
QLineEdit *text_2 = new QLineEdit();
text_2->setText("Sample text in the Center");
text_2->setMinimumSize(400, 35);
text_2->setAlignment(Qt::AlignHCenter);
QLineEdit *text_3 = new QLineEdit();
text_3->setText("Sample text on the Right");
text_3->setMinimumSize(400, 35);
text_3->setAlignment(Qt::AlignRight);
QPushButton *pb_1 = new QPushButton();
pb_1->setText("Close");
QVBoxLayout *layout1 = new QVBoxLayout();
layout1->addSpacing(75);
layout1->addWidget(text_1);
layout1->addSpacing(35);
layout1->addWidget(text_2);
layout1->addSpacing(35);
layout1->addWidget(text_3);
layout1->addSpacing(75);
QHBoxLayout *layout2 = new QHBoxLayout();
layout2->addStretch();
layout2->addWidget(pb_1);
layout2->addStretch();
QVBoxLayout *layoutMain = new QVBoxLayout(this);
layoutMain->addLayout(layout1);
layoutMain->addSpacing(75);
layoutMain->addLayout(layout2);
connect(pb_1, &QPushButton::clicked,
this, &QWidget::close);
}
Lines 9, 14, and 19 show how to specify the text should be left justified, centered, or right justified. When running this program you will be able to type in any of these edit fields. Make sure to type in the right justified line edit to see how new text is “added” on the right, while the existing text is pushed to the left.
Lines 24 through 41 are used to set the layout of our widgets. The addStretch() and addSpacing() methods specify where the extra white space should appear when the main window is resized by the user. CopperSpice will automatically adjust the size and position of all the widgets.
Main Function
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
MainWindow *window = new MainWindow();
window->show();
return app.exec();
}
The source code for main() is the same as shown in example 3.
Running the Example
To build and run this example use the same CMake build file and commands as we showed for the first example. The only suggested modification is on line 2 of the CMakeLists.txt file, change “example_1” to “example_5”.