Skip to content

CopperSpice Journal

CopperSpice Journal

Source Code  (Gui Example 2)

Posted on December 27, 2021April 11, 2022 By Barbara Geller

Our next example will add a new Push Button. When it is clicked, a built in dialog box will be displayed that allows the user to select a color.

#include <QtCore>
#include <QtGui>

int main(int argc, char *argv[])
{
   QApplication app(argc, argv);

   QWidget *mainWindow = new QWidget();
   mainWindow->setMinimumSize(700, 350);

   QPushButton *pb_1 = new QPushButton();
   pb_1->setText("Show Colors");

   QPushButton *pb_2 = new QPushButton();
   pb_2->setText("Close");

   QHBoxLayout *layout = new QHBoxLayout(mainWindow);
   layout->addStretch();
   layout->addWidget(pb_1);
   layout->addSpacing(10);
   layout->addWidget(pb_2);
   layout->addStretch();

   QObject::connect(pb_1, &QPushButton::clicked, 
         pb_1, []() { QColorDialog::getColor(Qt::green); });

   QObject::connect(pb_2, &QPushButton::clicked,
         mainWindow, &QWidget::close);

   mainWindow->show();

   return app.exec();
}

Lines 18 through 22 are expanded in this example to center the two push buttons in the window and add a spacing of 10 pixels between the buttons. If the user widens the application window the buttons will automatically stay relative to each other and centered on the screen.

Lines 24 and 25 add a new Signal / Slot connection for push button 1. The fourth parameter uses a different syntax than the method pointer syntax for push button 2. Although this syntax looks a bit odd, the end result is to call the getColor() method in the QColorDialog class.

The code shown below is a C++ lambda expression. The syntax requires a set of square brackets, parentheses, and then a block using curly braces. The source code in the curly braces is what will be invoked.

[]() { QColorDialog::getColor(Qt::green); }

The following video contains more information about Lambda Expressions.
https://www.youtube.com/watch?v=ZHw2XHij1is

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_2”.

https://download.copperspice.com/journal/example_02.zip

Uncategorized

Post navigation

Previous Post: Compile, Link, and Run  (Gui Example 1)
Next Post: Source Code  (Gui Example 3)
  • CopperSpice Journal Homepage
    • Table of Contents
    • Example Source Code
    • Discussion Forum
  • CopperSpice Homepage
  • Github Repository
  • Videos About C++

Post comments or questions on our CopperSpice Forum

Copyright © 2021-2025 CopperSpice