Opening a dialog to show color samples is interesting but now we want to do something with the selected color. With our new refactored code we can expand the MainWindow::setColor() method and add one new widget, without redesigning the application.
#include <QtCore>
#include <QtGui>
class MainWindow : public QWidget
{
public:
MainWindow();
private:
void setColor();
QLineEdit *text_1;
};
Our MainWindow class declaration has one new data member on Line 11. The declaration for the new line edit must be added so it can be accessed in the setColor() method.
MainWindow::MainWindow()
{
setMinimumSize(700, 350);
// text edit widget
text_1 = new QLineEdit();
text_1->setText("Sample text to show a background color");
text_1->setMinimumSize(400, 35);
// 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 *layout1 = new QHBoxLayout();
layout1->addSpacing(75);
layout1->addWidget(text_1);
layout1->addSpacing(75);
QHBoxLayout *layout2 = new QHBoxLayout();
layout2->addStretch();
layout2->addWidget(pb_1);
layout2->addSpacing(10);
layout2->addWidget(pb_2);
layout2->addStretch();
QVBoxLayout *layoutMain = new QVBoxLayout(this);
layoutMain->addLayout(layout1);
layoutMain->addSpacing(75);
layoutMain->addLayout(layout2);
QObject::connect(pb_1, &QPushButton::clicked,
this, &MainWindow::setColor);
QObject::connect(pb_2, &QPushButton::clicked,
this, &QWidget::close);
}
void MainWindow::setColor()
{
QColor color;
color = QColorDialog::getColor(Qt::green, this);
if (color.isValid()) {
QPalette tmp = text_1->palette();
tmp.setColor(QPalette::Base, color);
text_1->setPalette(tmp);
}
}
A new widget was added on lines 6 through 8. The QLineEdit widget is used to display a single line edit for the user to edit plain text. Standard editing operations like cut, copy, paste, undo, and redo are built into this CopperSpice GUI class. This widget was added so when the user selects a new color we can change the background color.
Layouts
Lines 18 through 28 create two QHBoxLayout objects. One is for the text edit and the other is for the two push buttons. Lines 30 through 33 create a QVBoxLayout object and both horizontal layouts are added to the vertical layout. At that point the widgets in the layouts are changed to have mainWindow as their parent.
SetColor()
The setColor() method has changed. Once the user selects a valid color it is used to change the background of the text edit.
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_4”.