Let’s take the prior example and refactor the source code to make it modular. This will give us the flexibility to add new functionality without affecting other areas of the software. One of the key advantages of our new code is the main() function is short and simple. All the code for the user interface is now encapsulated in a new class called MainWindow.
#include <QtCore>
#include <QtGui>
class MainWindow : public QWidget
{
public:
MainWindow();
void setColor();
};
MainWindow::MainWindow()
{
setMinimumSize(700, 350);
// two buttons
QPushButton *pb_1 = new QPushButton();
pb_1->setText("Show Colors");
QPushButton *pb_2 = new QPushButton();
pb_2->setText("Close");
// layout widgets on mainWindow
QHBoxLayout *layout = new QHBoxLayout(this);
layout->addStretch();
layout->addWidget(pb_1);
layout->addSpacing(10);
layout->addWidget(pb_2);
layout->addStretch();
QObject::connect(pb_1, &QPushButton::clicked,
this, &MainWindow::setColor);
QObject::connect(pb_2, &QPushButton::clicked,
this, &QWidget::close);
}
void MainWindow::setColor()
{
QColorDialog::getColor(Qt::green, this);
}
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
MainWindow *window = new MainWindow();
window->show();
return app.exec();
}
The first step in our refactor is to create a declaration for our new class, which we called MainWindow. The source code is shown shown on lines 4 through 9. Although this is traditional C++ code the inheritance for the MainWindow class from QWidget is very significant.
The QWidget class is the base class for all other widgets in CopperSpice. Classes like QComboBox, QLineEdit, and QMenu are derived from QWidget and can be used to create a graphical interface. The widget classes are located in the CopperSpice GUI library, which has the name CsGui. This is why the CsGui library must be linked with your user application.
Layouts
Lines 23 through 28 create a new QHBoxLayout object and the two push buttons are added to the layout. At that point the widgets in the layout are changed to have MainWindow as their parent.
Signal / Slot Connections
In our prior example we used a lambda expression in the QObject::connect() of the push button to call QColorDialog::getColor(). In this example we have changed the code to call a method of the MainWindow class. Refer to lines 30 through 34 above.
The fourth parameter to QObject::connect() now will invoke the setColor() method when the user clicks push button one. In our next example we will expand the functionality of this method.
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 say “example_3”.