CopperSpice API  1.9.1
Widget Overview

Widgets are the visual components for a graphical user interface application built with CopperSpice. Each GUI widget such as a push button, spin box, or a text label is placed somewhere on a main window, secondary window, or a child window. Widget classes inherit from QWidget, which inherits from QObject. QWidget is not an abstract class.

Some widgets like QGroupBox can contain other widgets. However, it would not make sense to put a combo box inside a push button.

Example 1 - Top Level Window

If a widget is created without a parent it is called a "top level window". Since there is no parent object the developer is responsible for destroying these widgets. In the following example a QWidget is created to display a window with a default size.

#include <QtGui>
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QWidget window;
window.resize(320, 240);
window.show();
window.setWindowTitle("Top-level widget");
return app.exec();
}

Example 2 - Child Widget

A child widget is added to the previous example by passing &window to the QPushButton constructor.

#include <QtGui>
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QWidget window;
window.resize(320, 240);
window.setWindowTitle("Child widget");
window.show();
QPushButton *button = new QPushButton("Press me", &window);
button->move(100, 100);
button->show();
return app.exec();
}

Example 3 - Using Layouts

Child widgets are normally arranged inside a window using layout objects instead of specifying positions and sizes explicitly. This example constructs a label and a line edit widget.

#include <QtGui>
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QLabel *label = new QLabel("Name:");
QLineEdit *lineEdit = new QLineEdit();
QHBoxLayout *layout = new QHBoxLayout();
layout->addWidget(label);
layout->addWidget(lineEdit);
QWidget window;
window.setLayout(layout);
window.setWindowTitle("Window layout");
window.show();
return app.exec();
}

Example 4 - Nested Layouts

Layouts are used to provide different levels of grouping for widgets. In this example a label is displayed next to a line edit at the top of a window. Below this a table view is displayed which shows the results of a database query. The query process was omitted for simplicity.

#include <QtGui>
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QWidget window;
QLabel *queryLabel = new QLabel("Query:");
QLineEdit *queryEdit = new QLineEdit();
QTableView *resultView = new QTableView();
QHBoxLayout *queryLayout = new QHBoxLayout();
queryLayout->addWidget(queryLabel);
queryLayout->addWidget(queryEdit);
QVBoxLayout *mainLayout = new QVBoxLayout();
mainLayout->addLayout(queryLayout);
mainLayout->addWidget(resultView);
window.setLayout(mainLayout);
// set up the model and configure the view (code omitted)
window.setWindowTitle("Nested layouts");
window.show();
return app.exec();
}