Skip to content

CopperSpice Journal

CopperSpice Journal

Source Code  (Gui Example 1)

Posted on December 22, 2021April 1, 2025 By Barbara Geller

This article shows the source code for our first example. It is a small C++ program which uses two of the CopperSpice libraries to display a window with a single Push Button. Pressing the button will close the program.

#include <QtCore>
#include <QtGui>

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

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

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

   QHBoxLayout *layout = new QHBoxLayout(mainWindow);
   layout->addWidget(pb);

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

   mainWindow->show();

   return app.exec();
}

This section will explain some of the more interesting lines of code. Lines 8 and 11 create new GUI elements using classes implemented in the CopperSpice CsGui library.

Line 9 is optional but without it, the default size of the window is extremely small since the space required for a push button is small. Setting the window to 700 x 350 will also widen the push button. In future examples we will show how to adjust the width of the button independently from the main window.

Line 20 is required or the mainWindow will never be displayed. Line 22 runs the program.

Signal / Slot Connection

The most noteworthy code in this example is lines 17 and 18. This creates a Signal / Slot connection. For a detailed description about this topic refer to Signals and Slots.

This code instructs the program to close the window and terminate the program when the push button is clicked. In later examples we will show more examples about Signals and Slots and how to do other fancy things.

The connect() method is passing 4 parameters. The first is the push button object which is the Sender of the Signal. The second parameter has the syntax of &QPushButton::clicked, and it is called a method pointer. This parameter identities what entity or thing in the QPushButton class will send the Signal we are interested in watching for.

The next parameter is the Receiver, which is the object that will be notified when the Signal event occurs. The Receiver is our mainWindow object. The last parameter is where we define what should happen with the Signal event happens. This is called the Slot and in our code the close() method for the mainWindow will be called.

Uncategorized

Post navigation

Previous Post: Definition of a Toolchain
Next Post: Build File  (Gui Example 1)
  • 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