# Icons Example

The Icons example shows how QIcon can generate pixmaps reflecting an icon's state, mode and size. These pixmaps are generated from the set of pixmaps made available to the icon, and are used by Qt widgets to show an icon representing a particular action.

Contents:

- QIcon Overview
- Overview of the Icons Application
- Line-by-Line Walkthrough

- IconPreviewArea Class Definition
- The Class Icon
- The IconSizeSpinBox Class
- The ImageDelegate Class

## QIcon Overview

The QIcon class provides scalable icons in different modes and states. An icon's state and mode are depending on the intended use of the icon. Qt currently defines four modes:

Mode | Description
--- | ---
QIcon::Normal | Display the pixmap when the user is not interacting with the icon, but the functionality represented by the icon is available.
QIcon::Active | Display the pixmap when the functionality represented by the icon is available and the user is interacting with the icon, for example, moving the mouse over it or clicking it.
QIcon::Disabled | Display the pixmap when the functionality represented by the icon is not available.
QIcon::Selected | Display the pixmap when the icon is selected.

QIcon's states are QIcon::On and QIcon::Off, which will display the pixmap when the widget is in the respective state. The most common usage of QIcon's states are when displaying checkable tool buttons or menu entries (see QAbstractButton::setCheckable() and QAction::setCheckable()). When a tool button or menu entry is checked, the QIcon's state is On, otherwise it's Off. You can, for example, use the QIcon's states to display differing pixmaps depending on whether the tool button or menu entry is checked or not.

A QIcon can generate smaller, larger, active, disabled, and selected pixmaps from the set of pixmaps it is given. Such pixmaps are used by Qt widgets to show an icon representing a particular action.

## Overview of the Icons Application

With the Icons application you get a preview of an icon's generated pixmaps reflecting its different states, modes and size.

When an image is loaded into the application, it is converted into a pixmap and becomes a part of the set of pixmaps available to the icon. An image can be excluded from this set by checking off the related checkbox. The application provides a sub directory containing sets of images explicitly designed to illustrate how Qt renders an icon in different modes and states.

The application allows you to manipulate the icon size with some predefined sizes and a spin box. The predefined sizes are style dependent, but most of the styles have the same values: Only the Macintosh style differ by using 32 pixels, instead of 16 pixels, for toolbar buttons. You can navigate between the available styles using the View menu.

The View menu also provide the option to make the application guess the icon state and mode from an image's file name. The File menu provide the options of adding an image and removing all images. These last options are also available through a context menu that appears if you press the right mouse button within the table of image files. In addition, the File menu provide an Exit option, and the Help menu provide information about the example and about Qt.

The screenshot above shows the application with one image file loaded. The Guess Image Mode/State is enabled and the style is Plastique.

When QIcon is provided with only one available pixmap, that pixmap is used for all the states and modes. In this case the pixmap's icon mode is set to normal, and the generated pixmaps for the normal and active modes will look the same. But in disabled and selected mode, Qt will generate a slightly different pixmap.

The next screenshot shows the application with an additional file loaded, providing QIcon with two available pixmaps. Note that the new image file's mode is set to disabled. When rendering the Disabled mode pixmaps, Qt will now use the new image. We can see the difference: The generated disabled pixmap in the first screenshot is slightly darker than the pixmap with the originally set disabled mode in the second screenshot.

When Qt renders the icon's pixmaps it searches through the set of available pixmaps following a particular algorithm. The algorithm is documented in QIcon, but we will describe some particular cases below.

In the screenshot above, we have set `monkey_on_32x32` to be an Active/On pixmap and `monkey_off_64x64` to be Normal/Off. To render the other six mode/state combinations, QIcon uses the search algorithm described in the table below:

Requested Pixmap | Preferred Alternatives (mode/state)
--- | ---
Mode | State | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8
Normal | Off | N0 | A0 | N1 | A1 | D0 | S0 | D1 | S1
On | N1 | A1 | N0 | A0 | D1 | S1 | D0 | S0
Active | Off | A0 | N0 | A1 | N1 | D0 | S0 | D1 | S1
On | A1 | N1 | A0 | N0 | D1 | S1 | D0 | S0
Disabled | Off | D0 | N0' | A0' | D1 | N1' | A1' | S0' | S1'
On | D1 | N1' | A1' | D0 | N0' | A0' | S1' | S0'
Selected | Off | S0 | N0'' | A0'' | S1 | N1'' | A1'' | D0'' | D1''
On | S1 | N1'' | A1'' | S0 | N0'' | A0'' | D1'' | D0''

In the table, "0" and "1" stand for Off" and "On", respectively. Single quotes indicates that QIcon generates a disabled ("grayed out") version of the pixmap; similarly, double quuote indicate that QIcon generates a selected ("blued out") version of the pixmap.

The alternatives used in the screenshot above are shown in bold. For example, the Disabled/Off pixmap is derived by graying out the Normal/Off pixmap (`monkey_off_64x64`).

In the next screenshots, we loaded the whole set of monkey images. By checking or unchecking file names from the image list, we get different results:

For any given mode/state combination, it is possible to specify several images at different resolutions. When rendering an icon, QIcon will automatically pick the most suitable image and scale it down if necessary. (QIcon never scales up images, because this rarely looks good.)

The screenshots below shows what happens when we provide QIcon with three images (`qtopia_16x16.png`, `qtopia_32x32.png`, `qtopia_48x48.png`) and try to render the QIcon at various resolutions:

| 8 x 8 | 16 x 16 | 17 x 17
32 x 32 | 33 x 33 | 48 x 48 | 64 x 64

For sizes up to 16 x 16, QIcon uses `qtopia_16x16.png` and scales it down if necessary. For sizes between 17 x 17 and 32 x 32, it uses `qtopia_32x32.png`. For sizes above 32 x 32, it uses `qtopia_48x48.png`.

## Line-by-Line Walkthrough

The Icons example consists of four classes:

- `MainWindow` inherits QMainWindow and is the main application window.
- `IconPreviewArea` is a custom widget that displays all combinations of states and modes for a given icon.
- `IconSizeSpinBox` is a subclass of QSpinBox that lets the user enter icon sizes (e.g., "48 x 48").
- `ImageDelegate` is a subclass of QItemDelegate that provides comboboxes for letting the user set the mode and state associated with an image.

We will start by reviewing the `IconPreviewArea` class before we take a look at the `MainWindow` class. Finally, we will review the `IconSizeSpinBox` and `ImageDelegate` classes.

### IconPreviewArea Class Definition

An `IconPreviewArea` widget consists of a group box containing a grid of QLabel widgets displaying headers and pixmaps.

The `IconPreviewArea` class inherits QWidget. It displays the generated pixmaps corresponding to an icon's possible states and modes at a given size.

We will now review the IconPreviewArea's implementation:

(I think we need to say something about the data members)

                public IconPreviewArea()
                {
                    QGridLayout mainLayout = new QGridLayout();
                    setLayout(mainLayout);

                    icon = new QIcon();

                    stateLabels[0] = createHeaderLabel(tr("Off"));
                    stateLabels[1] = createHeaderLabel(tr("On"));

                    modeLabels[0] = createHeaderLabel(tr("Normal"));
                    modeLabels[1] = createHeaderLabel(tr("Active"));
                    modeLabels[2] = createHeaderLabel(tr("Disabled"));
                    modeLabels[3] = createHeaderLabel(tr("Selected"));

                    for (int j = 0; j < NumStates; ++j)
                        mainLayout.addWidget(stateLabels[j], j + 1, 0);

                    for (int i = 0; i < NumModes; ++i) {
                        mainLayout.addWidget(modeLabels[i], 0, i + 1);

                        for (int j = 0; j < NumStates; ++j) {
                            pixmapLabels[i][j] = createPixmapLabel();
                            mainLayout.addWidget(pixmapLabels[i][j], j + 1, i + 1);
                        }
                    }
                }

In the constructor we create the labels displaying the headers and the icon's generated pixmaps, and add them to a grid layout.

                public void setIcon(QIcon icon)
                {
                    this.icon = icon;
                    updatePixmapLabels();
                }
                public void setSize(QSize size)
                {
                    if (size != this.size) {
                        this.size = size;
                        updatePixmapLabels();
                    }
                }

The public `setIcon()` and `setSize()` methods change the icon or the icon size, and make sure that the generated pixmaps are updated.

                private QLabel createHeaderLabel(String text)
                {
                    QLabel label = new QLabel(tr("<b>"+text+"</b>"));
                    label.setAlignment(Qt.AlignmentFlag.AlignCenter);
                    return label;
                }
                private QLabel createPixmapLabel()
                {
                    QLabel label = new QLabel();
                    label.setEnabled(false);
                    label.setAlignment(Qt.AlignmentFlag.AlignCenter);
                    label.setFrameShape(QFrame.Shape.Box);
                    label.setSizePolicy(QSizePolicy.Policy.Expanding,
                                        QSizePolicy.Policy.Expanding);
                    label.setBackgroundRole(QPalette.ColorRole.Base);
                    label.setAutoFillBackground(true);
                    label.setMinimumSize(132, 132);
                    return label;
                }

We use the `createHeaderLabel()` and `createPixmapLabel()` methods to create the preview area's labels displaying the headers and the icon's generated pixmaps. Both methods return the QLabel that is created.

                private void updatePixmapLabels()
                {
                    for (int i = 0; i < NumModes; ++i) {
                        QIcon.Mode mode;
                        if (i == 0) {
                            mode = QIcon.Mode.Normal;
                        } else if (i == 1) {
                            mode = QIcon.Mode.Active;
                        } else if (i == 2) {
                            mode = QIcon.Mode.Disabled;
                        } else {
                            mode = QIcon.Mode.Selected;
                        }

                        for (int j = 0; j < NumStates; ++j) {
                            QIcon.State state = (j == 0) ? QIcon.State.Off : QIcon.State.On;
                            QPixmap pixmap = icon.pixmap(size, mode, state);
                            pixmapLabels[i][j].setPixmap(pixmap);
                            pixmapLabels[i][j].setEnabled(!pixmap.isNull());
                        }
                    }
                }

We use the private `updatePixmapLabel()` method to update the generated pixmaps displayed in the preview area.

For each mode, and for each state, we retrieve a pixmap using the QIcon::pixmap() method, which generates a pixmap corresponding to the given state, mode and size.

### The Class Icon

The `Icons` widget consists of three main elements: an images group box, an icons size group box and a preview area.

The Icons class inherits from QMainWindow. We reimplement the constructor, and declare several private slots:

- The `about()` slot simply provides information about the example.
- The `changeStyle()` slot changes the application's GUI style and adjust the style dependent size options.
- The `changeSize()` slot changes the size of the preview area's icon.
- The `changeIcon()` slot updates the set of pixmaps available to the icon displayed in the preview area.
- The `addImage()` slot allows the user to load a new image into the application.

In addition we declare several private methods - which will be examined later - to simplify the constructor. We will now review the implementation of the Icons class

            public Icons()
            {
                centralWidget = new QWidget();
                setCentralWidget(centralWidget);

                createPreviewGroupBox();
                createImagesGroupBox();
                createIconSizeGroupBox();

                createActions();
                createMenus();
                createContextMenu();

                QGridLayout mainLayout = new QGridLayout();
                mainLayout.addWidget(previewGroupBox, 0, 0, 1, 2);
                mainLayout.addWidget(imagesGroupBox, 1, 0);
                mainLayout.addWidget(iconSizeGroupBox, 1, 1);
                centralWidget.setLayout(mainLayout);

                setWindowTitle(tr("Icons"));
                otherRadioButton.click();

                resize(minimumSizeHint());
            }

In the constructor, we first create the main window's central widget and its child widgets, and put them in a grid layout. Then we create the menus with their associated entries and actions.

Before we resize the application window to a suitable size, we set the window title and determine the current style for the application. We also enable the icon size spin box by clicking the associated radio button, making the current value of the spin box the icon's initial size.

            private void about()
            {
                QMessageBox.about(this, tr("About Icons"),
                    tr("The <b>Icons</b> example illustrates how Qt renders an icon in "+
                       "different modes (active, normal, disabled, and selected) and "+
                       "states (on and off) based on a set of images."));
            }

The `about()` slot displays a message box using the static QMessageBox::about() method. In this example it displays a simple box with information about the example.

The `about()` method looks for a suitable icon in four locations: It prefers its parent's icon if that exists. If it doesn't, the method tries the top-level widget containing parent, and if that fails, it tries the active window. As a last resort it uses the QMessageBox's Information icon.

            private void changeStyle(boolean checked)
            {
                if (!checked)
                    return;

                QAction action = (QAction) QSignalEmitter.signalSender();

In the `changeStyle()` slot we first check the slot's parameter. If it is false we immediately return, otherwise we find out which style to change to, i.e. which action that triggered the slot, using the QSignalEmitter.signalSender() method.

This method returns the sender as a QSignalEmitter. Since we know that the sender is a QAction object, we can safely cast the QSignalEmitter object.

                QStyle style = QStyleFactory.create((String) action.data());
                if (style != null) {
                    QApplication.setStyle(style);
                    QApplication.setPalette(style.standardPalette());
                }

                int smallIconSize = style.pixelMetric(QStyle.PixelMetric.PM_SmallIconSize);
                smallRadioButton.setText("Small (" + smallIconSize + " x " + smallIconSize + ")");

                int largeIconSize = style.pixelMetric(QStyle.PixelMetric.PM_LargeIconSize);
                largeRadioButton.setText("Large (" + largeIconSize + " x " + largeIconSize + ")");

                int toolBarIconSize = style.pixelMetric(QStyle.PixelMetric.PM_ToolBarIconSize);
                toolBarRadioButton.setText("Toolbars (" + toolBarIconSize + " x " + toolBarIconSize + ")");

                int listViewIconSize = style.pixelMetric(QStyle.PixelMetric.PM_ListViewIconSize);
                listViewRadioButton.setText("List views (" + listViewIconSize + " x " + listViewIconSize + ")");

                int iconViewIconSize = style.pixelMetric(QStyle.PixelMetric.PM_IconViewIconSize);
                iconViewRadioButton.setText("Icon views (" + iconViewIconSize + " x " + iconViewIconSize + ")");

                int tabBarIconSize = style.pixelMetric(QStyle.PixelMetric.PM_TabBarIconSize);
                tabBarRadioButton.setText("Tab bars (" + tabBarIconSize + " x " + tabBarIconSize + ")");

                changeSize(true);
            }

Once we have the action, we extract the style name using QAction::data(). Then we create a QStyle object using the static QStyleFactory::create() method.

As a precaution, we check that the style is valid before we use the QApplication::setStyle() method to set the application's GUI style to the new style.

The predefined icon size options provided in the application are style dependent, so we need to update the labels in the icon size group box and in the end call the `changeSize()` slot to update the icon's size.

            private void changeSize(int value)
            {
                changeSize(true);
            }

The `changeSize()` slot sets the size for the preview area's icon.

To determine the new size we first check if the spin box is enabled. If it is, we extract the extent of the new size from the box. If it's not, we search through the predefined size options, extract the QStyle::PixelMetric and use the QStyle::pixelMetric() method to determine the extent. Then we create a QSize object based on the extent, and use that object to set the size of the preview area's icon.

            private void addImages()
            {
                List<String> fileNames = QFileDialog.getOpenFileNames(this,
                                            tr("Open Images"), "",
                                            new QFileDialog.Filter(tr("Images (*.png *.xpm *.jpg);;"+
                                               "All Files (*)")));
                if (!fileNames.isEmpty()) {
                    for (String fileName : fileNames) {
                        int row = imagesTable.rowCount();
                        imagesTable.setRowCount(row + 1);

The first thing we do when the `addImages()` slot is called, is to show a file dialog to the user. The easiest way to create a file dialog is to use QFileDialog's static methods. Here we use the getOpenFileNames() method, which will return one or more existing files selected by the user.

For each of the files the file dialog returns, we add a row to the table widget. The table widget is listing the images the user has loaded into the application.

                        String imageName = new QFileInfo(fileName).baseName();
                        QTableWidgetItem item0 = new QTableWidgetItem(imageName);
                        item0.setData(Qt.ItemDataRole.UserRole, fileName);
                        Qt.ItemFlags flags = item0.flags();
                        flags.clear(Qt.ItemFlag.ItemIsEditable);

We retrieve the image name using the QFileInfo::baseName() method that returns the base name of the file without the path, and create the first table widget item in the row. Then we add the file's complete name to the item's data. Since an item can hold several information pieces, we need to assign the file name a role that will distinguish it from other data. This role can be Qt.ItemDataRole.UserRole or any value above it.

We also make sure that the item is not editable by removing the Qt.ItemFlag.ItemIsEditable flag. Table items are editable by default.

                        QTableWidgetItem item1 = new QTableWidgetItem(tr("Normal"));
                        QTableWidgetItem item2 = new QTableWidgetItem(tr("Off"));

                        if (guessModeStateAct.isChecked()) {
                            if (fileName.contains("_act")) {
                                item1.setText(tr("Active"));
                            } else if (fileName.contains("_dis")) {
                                item1.setText(tr("Disabled"));
                            } else if (fileName.contains("_sel")) {
                                item1.setText(tr("Selected"));
                            }

                            if (fileName.contains("_on"))
                                item2.setText(tr("On"));
                        }

Then we create the second and third items in the row making the default mode Normal and the default state Off. But if the Guess Image Mode/State option is checked, and the file name contains "_act", "_dis", or "_sel", the modes are changed to Active, Disabled, or Selected. And if the file name contains "_on", the state is changed to On. The sample files in the example's `images` subdirectory respect this naming convension.

                        imagesTable.setItem(row, 0, item0);
                        imagesTable.setItem(row, 1, item1);
                        imagesTable.setItem(row, 2, item2);
                        imagesTable.openPersistentEditor(item1);
                        imagesTable.openPersistentEditor(item2);

                        item0.setCheckState(Qt.CheckState.Checked);
                    }
                }
            }

In the end we add the items to the associated row, and use the QTableWidget::openPersistentEditor() method to create comboboxes for the mode and state columns of the items.

Due to the the connection between the table widget's itemChanged() signal and the `changeIcon()` slot, the new image is automatically converted into a pixmap and made part of the set of pixmaps available to the icon in the preview area. So we need to make sure that the new image's check box is enabled.

            private void changeIcon()
            {
                QIcon icon = new QIcon();

                for (int row = 0; row < imagesTable.rowCount(); ++row) {
                    QTableWidgetItem item0 = imagesTable.item(row, 0);
                    QTableWidgetItem item1 = imagesTable.item(row, 1);
                    QTableWidgetItem item2 = imagesTable.item(row, 2);

                    if (item0.checkState() == Qt.CheckState.Checked) {
                        QIcon.Mode mode;
                        if (item1.text().equals(tr("Normal"))) {
                            mode = QIcon.Mode.Normal;
                        } else if (item1.text().equals(tr("Active"))) {
                            mode = QIcon.Mode.Active;
                        } else if (item1.text().equals(tr("Disabled"))) {
                            mode = QIcon.Mode.Disabled;
                        } else {
                            mode = QIcon.Mode.Selected;
                        }

                        QIcon.State state;
                        if (item2.text().equals(tr("On"))) {
                            state = QIcon.State.On;
                        } else {
                            state = QIcon.State.Off;
                        }

The `changeIcon()` slot is called when the user alters the set of images listed in the QTableWidget to update the QIcon object rendered by the `IconPreviewArea`.

We first create a QIcon object, and then we run through the QTableWidget, which lists the images the user has loaded into the application.

                        String fileName = (String) item0.data(Qt.ItemDataRole.UserRole);
                        QImage image = new QImage(fileName);
                        if (!image.isNull())
                            icon.addPixmap(QPixmap.fromImage(image), mode, state);
                    }
                }

We also extract the image file's name using the QTableWidgetItem::data() method. This method takes a Qt::DataItemRole as an argument to retrieve the correct data (remember that an item can hold several pieces of information) and returns it as an Object. Then we use the QVariant::toString() method to get the file name as a QString.

To create a pixmap from the file, we need to first create an image and then convert this image into a pixmap using QPixmap::fromImage(). Once we have the final pixmap, we add it, with its associated mode and state, to the QIcon's set of available pixmaps.

                previewArea.setIcon(icon);
            }

After running through the entire list of images, we change the icon of the preview area to the one we just created.

            private void removeAllImages()
            {
                imagesTable.setRowCount(0);
                changeIcon();
            }

In the `removeAllImages()` slot, we simply set the table widget's row count to zero, automatically removing all the images the user has loaded into the application. Then we update the set of pixmaps available to the preview area's icon using the `changeIcon()` slot.

The `createImagesGroupBox()` method is implemented to simplify the constructor. The main purpose of the method is to create a QTableWidget that will keep track of the images the user has loaded into the application.

            private void createImagesGroupBox()
            {
                imagesGroupBox = new QGroupBox(tr("Images"));

                imagesTable = new QTableWidget();
                imagesTable.setSelectionMode(QAbstractItemView.SelectionMode.NoSelection);
                imagesTable.setItemDelegate(new ImageDelegate(this));

First we create a group box that will contain the table widget. Then we create a QTableWidget and customize it to suit our purposes.

We call QAbstractItemView::setSelectionMode() to prevent the user from selecting items.

The QAbstractItemView::setItemDelegate() call sets the item delegate for the table widget. We create a `ImageDelegate` that we make the item delegate for our view.

The QItemDelegate class can be used to provide an editor for an item view class that is subclassed from QAbstractItemView. Using a delegate for this purpose allows the editing mechanism to be customized and developed independently from the model and view.

In this example we derive `ImageDelegate` from QItemDelegate. QItemDelegate usually provides line editors, while our subclass `ImageDelegate`, provides comboboxes for the mode and state fields.

                List<String> labels = new LinkedList<String>();
                labels.add(tr("Image"));
                labels.add(tr("Mode"));
                labels.add(tr("State"));

                imagesTable.horizontalHeader().setDefaultSectionSize(90);
                imagesTable.setColumnCount(3);
                imagesTable.setHorizontalHeaderLabels(labels);
                imagesTable.horizontalHeader().setResizeMode(0, QHeaderView.ResizeMode.Stretch);
                imagesTable.horizontalHeader().setResizeMode(1, QHeaderView.ResizeMode.Fixed);
                imagesTable.horizontalHeader().setResizeMode(2, QHeaderView.ResizeMode.Fixed);
                imagesTable.verticalHeader().hide();

Then we customize the QTableWidget's horizontal header, and hide the vertical header.

                imagesTable.itemChanged.connect(this, "changeIcon()");
                QVBoxLayout layout = new QVBoxLayout();
                layout.addWidget(imagesTable);
                imagesGroupBox.setLayout(layout);
            }

At the end, we connect the QTableWidget::itemChanged() signal to the `changeIcon()` slot to ensuret that the preview area is in sync with the image table.

The `createIconSizeGroupBox()` method is called from the constructor. It creates the widgets controlling the size of the preview area's icon.

            private void createIconSizeGroupBox()
            {
                iconSizeGroupBox = new QGroupBox(tr("Icon Size"));

                smallRadioButton = new QRadioButton();
                largeRadioButton = new QRadioButton();
                toolBarRadioButton = new QRadioButton();
                listViewRadioButton = new QRadioButton();
                iconViewRadioButton = new QRadioButton();
                tabBarRadioButton = new QRadioButton();
                otherRadioButton = new QRadioButton(tr("Other:"));

                otherSpinBox = new IconSizeSpinBox();
                otherSpinBox.setRange(8, 128);
                otherSpinBox.setValue(64);

First we create a group box that will contain all the widgets. Then we create the radio buttons and the spin box.

The spin box is not a regular QSpinBox but an `IconSizeSpinBox`. The `IconSizeSpinBox` class inherits QSpinBox and reimplements two methods: QSpinBox::textFromValue() and QSpinBox::valueFromText(). The `IconSizeSpinBox` is designed to handle icon sizes, e.g., "32 x 32", instead of plain integer values.

                smallRadioButton.toggled.connect(this, "changeSize(boolean)");
                largeRadioButton.toggled.connect(this, "changeSize(boolean)");
                toolBarRadioButton.toggled.connect(this, "changeSize(boolean)");
                listViewRadioButton.toggled.connect(this, "changeSize(boolean)");
                iconViewRadioButton.toggled.connect(this, "changeSize(boolean)");
                tabBarRadioButton.toggled.connect(this, "changeSize(boolean)");
                otherRadioButton.toggled.connect(this, "changeSize(boolean)");
                otherSpinBox.valueChanged.connect(this, "changeSize(int)");

                QHBoxLayout otherSizeLayout = new QHBoxLayout();
                otherSizeLayout.addWidget(otherRadioButton);
                otherSizeLayout.addWidget(otherSpinBox);
                otherSizeLayout.addStretch();

                QGridLayout layout = new QGridLayout();
                layout.addWidget(smallRadioButton, 0, 0);
                layout.addWidget(largeRadioButton, 1, 0);
                layout.addWidget(toolBarRadioButton, 2, 0);
                layout.addWidget(listViewRadioButton, 0, 1);
                layout.addWidget(iconViewRadioButton, 1, 1);
                layout.addWidget(tabBarRadioButton, 2, 1);
                layout.addLayout(otherSizeLayout, 3, 0, 1, 2);
                layout.setRowStretch(4, 1);
                iconSizeGroupBox.setLayout(layout);
            }

Then we connect all of the radio buttons toggled() signals and the spin box's valueChanged() signal to the `changeSize()` slot to make sure that the size of the preview area's icon is updated whenever the user changes the icon size. In the end we put the widgets in a layout that we install on the group box.

            private void createActions()
            {
                addImagesAct = new QAction(tr("&Add Images..."), this);
                addImagesAct.setShortcut(tr("Ctrl+A"));
                addImagesAct.triggered.connect(this, "addImages()");

                removeAllImagesAct = new QAction(tr("&Remove All Images"), this);
                removeAllImagesAct.setShortcut(tr("Ctrl+R"));
                removeAllImagesAct.triggered.connect(this, "removeAllImages()");

                exitAct = new QAction(tr("&Quit"), this);
                exitAct.setShortcut(tr("Ctrl+Q"));
                exitAct.triggered.connect(this, "close()");

                styleActionGroup = new QActionGroup(this);
                for (String styleName : QStyleFactory.keys()) {
                    QAction action = new QAction(styleActionGroup);
                    action.setText(styleName + " Style");
                    action.setData(styleName);
                    action.setCheckable(true);
                    action.triggered.connect(this, "changeStyle(boolean)");
                }

                guessModeStateAct = new QAction(tr("&Guess Image Mode/State"), this);
                guessModeStateAct.setCheckable(true);
                guessModeStateAct.setChecked(true);

                aboutAct = new QAction(tr("&About"), this);
                aboutAct.triggered.connect(this, "about()");

                aboutQtAct = new QAction(tr("About &Qt"), this);
                aboutQtAct.triggered.connect(QApplication.instance(), "aboutQt()");
            }

In the `createActions()` method we create and customize all the actions needed to implement the functionality associated with the menu entries in the application.

In particular we create the `styleActionGroup` based on the currently available GUI styles using QStyleFactory. QStyleFactory::keys() returns a list of valid keys, typically including "windows", "motif", "cde", and "plastique". Depending on the platform, "windowsxp" and "macintosh" may be available.

We create one action for each key, and adds the action to the action group. Also, for each action, we call QAction::setData() with the style name. We will retrieve it later using QAction::data().

            private void createMenus()
            {
                fileMenu = menuBar().addMenu(tr("&File"));
                fileMenu.addAction(addImagesAct);
                fileMenu.addAction(removeAllImagesAct);
                fileMenu.addSeparator();
                fileMenu.addAction(exitAct);

                viewMenu = menuBar().addMenu(tr("&View"));
                for (QAction action : styleActionGroup.actions())
                    viewMenu.addAction(action);
                viewMenu.addSeparator();
                viewMenu.addAction(guessModeStateAct);

                menuBar().addSeparator();

                helpMenu = menuBar().addMenu(tr("&Help"));
                helpMenu.addAction(aboutAct);
                helpMenu.addAction(aboutQtAct);
            }

In the `createMenu()` method, we add the previously created actions to the File, View and Help menus.

The QMenu class provides a menu widget for use in menu bars, context menus, and other popup menus. We put each menu in the application's menu bar, which we retrieve using QMainWindow::menuBar().

            private void createContextMenu()
            {
                imagesTable.setContextMenuPolicy(Qt.ContextMenuPolicy.ActionsContextMenu);
                imagesTable.addAction(addImagesAct);
                imagesTable.addAction(removeAllImagesAct);
            }

QWidgets have a contextMenuPolicy property that controls how the widget should behave when the user requests a context menu (e.g., by right-clicking). We set the QTableWidget's context menu policy to Qt::ActionsContextMenu, meaning that the QActions associated with the widget should appear in its context menu.

Then we add the Add Image and Remove All Images actions to the table widget. They will then appear in the table widget's context menu.

            private void checkCurrentStyle()
            {
                for (QAction action : styleActionGroup.actions()) {
                    String styleName = action.data().toString();
                    QStyle candidate = QStyleFactory.create(styleName);

                    if (candidate.objectName().equals(
                            QApplication.style().objectName())) {
                        action.trigger();
                        return;
                    }
                }
            }

In the `checkCurrentStyle()` method we go through the group of style actions, looking for the current GUI style.

For each action, we first extract the style name using QAction::data(). Since this is only a QStyleFactory key (e.g., "macintosh"), we cannot compare it directly to the current style's class name. We need to create a QStyle object using the static QStyleFactory::create() method and compare the class name of the created QStyle object with that of the current style.

### The IconSizeSpinBox Class

The `IconSizeSpinBox` class is a subclass of QSpinBox. A plain QSpinBox can only handle integers. But since we want to display the spin box's values in a more sophisticated way, we need to subclass QSpinBox and reimplement the QSpinBox::textFromValue() and QSpinBox::valueFromText() methods.

The IconSizeSpinBox does not implement a constructor, so we move on to the `textFromValue` method:

                public String textFromValue(int value)
                {
                    return "" + value +" x " + value;
                }

QSpinBox::textFromValue() is used by the spin box whenever it needs to display a value. The default implementation returns a base 10 representation of the `value` parameter.

Our reimplementation returns a QString of the form "32 x 32".

                public int valueFromText(String text)
                {
                    QRegExp regExp = new QRegExp(tr("(\\d+)(\\s*[xx]\\s*\\d+)?"));

                    if (regExp.exactMatch(text)) {
                        return Integer.parseInt(regExp.cap(1));
                    } else {
                        return 0;
                    }
                }

The QSpinBox::valueFromText() method is used by the spin box whenever it needs to interpret text typed in by the user. Since we reimplement the `textFromValue()` method we also need to reimplement the `valueFromText()` method to interpret the parameter text and return the associated int value.

We parse the text using a regular expression (a QRegExp). We define an expression that matches one or several digits, optionally followed by whitespace, an "x" or the times symbol, whitespace and one or several digits again.

The first digits of the regular expression are captured using parentheses. This enables us to use the QRegExp::cap() or QRegExp::capturedTexts() methods to extract the matched characters. If the first and second numbers of the spin box value differ (e.g., "16 x 24"), we use the first number.

When the user presses Enter, QSpinBox first calls QSpinBox::valueFromText() to interpret the text typed by the user, then QSpinBox::textFromValue() to present it in a canonical format (e.g., "16 x 16").

### The ImageDelegate Class

The `ImageDelegate` class is a subclass of QItemDelegate. The QItemDelegate class provides display and editing facilities for data items from a model. A single QItemDelegate object is responsible for all items displayed in a item view (in our case, a QTableWidget).

A QItemDelegate can be used to provide an editor for an item view class that is subclassed from QAbstractItemView. Using a delegate for this purpose allows the editing mechanism to be customized and developed independently from the model and view.

The default implementation of QItemDelegate creates a QLineEdit. Since we want the editor to be a QComboBox, we need to subclass QItemDelegate and reimplement the QItemDelegate::createEditor(), QItemDelegate::setEditorData() and QItemDelegate::setModelData() methods.

We also implement `emitCommitData()`, which is a slot used to emit the QImageDelegate::commitData() signal with the appropriate argument.

We move on to examine the implementation of the individual methods.

                public ImageDelegate(QWidget widget)
                {
                    super(widget);
                }

The constructor is trivial.

                public QWidget createEditor(QWidget parent, QStyleOptionViewItem option,
                                            QModelIndex index)
                {
                    QComboBox comboBox = new QComboBox(parent);
                    if (index.column() == 1) {
                        comboBox.addItem(tr("Normal"));
                        comboBox.addItem(tr("Active"));
                        comboBox.addItem(tr("Disabled"));
                        comboBox.addItem(tr("Selected"));
                    } else if (index.column() == 2) {
                        comboBox.addItem(tr("Off"));
                        comboBox.addItem(tr("On"));
                    }

                    comboBox.activated.connect(this, "emitCommitData()");

                    return comboBox;
                }

The default QItemDelegate::createEditor() implementation returns the widget used to edit the item specified by the model and item index for editing. The parent widget and style option are used to control the appearance of the editor widget.

Our reimplementation create and populate a combobox instead of the default line edit. The contents of the combobox depends on the column in the table for which the editor is requested. Column 1 contains the QIcon modes, whereas column 2 contains the QIcon states.

In addition, we connect the combobox's activated() signal to the `emitCommitData()` slot to emit the QAbstractItemDelegate::commitData() signal whenever the user chooses an item using the combobox. This ensures that the rest of the application notices the change and updates itself.

                public void setEditorData(QWidget editor, QModelIndex index)
                {
                    QComboBox comboBox = (QComboBox) editor;
                    if (comboBox == null)
                        return;

                    int pos = comboBox.findText((String) index.model().data(index),
                                                 Qt.MatchFlag.MatchExactly);
                    comboBox.setCurrentIndex(pos);
                }

The QItemDelegate::setEditorData() method is used by QTableWidget to transfer data from a QTableWidgetItem to the editor. The data is stored as a string; we use QComboBox::findText() to locate it in the combobox.

Delegates work in terms of models, not items. This makes it possible to use them with any item view class (e.g., QListView, QListWidget, QTreeView, etc.). The transition between model and items is done implicitly by QTableWidget; we don't need to worry about it.

                public void setModelData(QWidget editor, QAbstractItemModel model,
                                         QModelIndex index)
                {
                    QComboBox comboBox = (QComboBox) editor;
                    if (comboBox == null)
                        return;

                    model.setData(index, comboBox.currentText());
                }

The QItemDelegate::setEditorData() method is used by QTableWidget to transfer data back from the editor to the QTableWidgetItem.

                private void emitCommitData()
                {
                    commitData.emit((QWidget) QSignalEmitter.signalSender());
                }

The `emitCommitData()` slot simply emit the QAbstractItemDelegate::commitData() signal for the editor that triggered the slot. This signal must be emitted when the editor widget has completed editing the data, and wants to write it back into the model.