Working with QImage, QSettings, and QByteArray in Qt

QImage

Indexed color mode allows pixels to store an index referencing a color lookup table rather than direct RGB values. Qt supports this through QImage::Format_Indexed8, which utilizes 8 bits per pixel to hold the index.

In an 8-bit grayscale indexed image, 256 distinct shades exist. A color table containing 256 entries with equal Red, Green, and Blue components is generated. The raw pixel data contains only integer indices and cannot be rendered directly. During painting, the rendering engine resolves the index against the color table to determine the actual grayscale RGB value.

Key methods include:

  • const uchar *QImage::constBits() const: Retrieves a pointer to the first pixel. Since QImage employs implicit sharing, this avoids a deep copy as the returned data is constant.
  • const uchar *QImage::constScanLine(int i) const: Fetches a pointer to the pixel data at scan line index i, starting at 0.
  • void QImage::setColorCount(int colorCount): Resizes the color table to hold colorCount entries. Any newly added entries default to transparent (qRgba(0,0,0,0)). The table must accommodate all index values present in the image data; otherwise, behavior is undefined.
  • void QImage::setColor(int index, QRgb colorValue): Assigns an ARGB color value to a specific index in the color table. If index exceeds the current table size, setColorCount() is invoked to expand it.

Example of populating a grayscale color table for an 8-bit indexed image and saving it:

QImage grayscaleImg(reinterpret_cast<uchar*>(buffer.ptr()), imgWidth, imgHeight, (imgWidth + 3) / 4 * 4, QImage::Format_Indexed8);
if (grayscaleImg.depth() == 8) {
    grayscaleImg.setColorCount(256);
    for (int shade = 0; shade < 256; ++shade) {
        grayscaleImg.setColor(shade, qRgb(shade, shade, shade));
    }
}
grayscaleImg.save("output_image.bmp", "bmp");

QSettings

QSettings provides persistent storage for application settings, typically utilizing INI files for configuration management.

Key methods include:

  • QSettings(const QString &fileName, QSettings::Format format, QObject *parent = nullptr): Initializes the settings object. When format is QSettings::IniFormat, it targets an INI file specified by fileName.
  • void setValue(const QString &key, const QVariant &value): Persists a value under the designated key.
  • QVariant value(const QString &key, const QVariant &defaultValue = QVariant()) const: Retrieves the value for the given key, returning a QVariant. Returns defaultValue if the key is absent.

Example of reading and writing standard values:

#include <QSettings>
#include <QApplication>

QSettings prefs(QApplication::applicationDirPath() + "/settings/app_config.ini", QSettings::IniFormat);

// Store values
prefs.setValue("/Layout/marginX", marginXVal);
prefs.setValue("/Layout/marginY", marginYVal);

// Retrieve values
int retrievedX = prefs.value("/Layout/marginX").toInt();
int retrievedY = prefs.value("/Layout/marginY").toInt();

By default, QSettings may not handle multi-byte characters properly in INI files unless the codec is explicitly defined. Specifying UTF-8 encoding ensures characters are stored correctly rather than as escaped byte sequences.

void ConfigManager::loadSettings()
{
    QSettings cfgObj(ConfigManager::filePath, QSettings::IniFormat);
    cfgObj.setIniCodec("utf-8");

    cfgObj.beginGroup("NetworkSetup");
    ConfigManager::serverName = cfgObj.value("Server", ConfigManager::serverName).toString();
    cfgObj.endGroup();
}

void ConfigManager::storeSettings()
{
    QSettings cfgObj(ConfigManager::filePath, QSettings::IniFormat);
    cfgObj.setIniCodec("utf-8");

    cfgObj.beginGroup("NetworkSetup");
    cfgObj.setValue("Server", ConfigManager::serverName);
    cfgObj.endGroup();
}

QByteArray

QByteArray serves as an advanced, memory-managed alternative to the standard C-style char*. It dynamically allocates memory to handle raw byte and string data efficiently.

Common constructors:

// Initializes an empty byte array
QByteArray::QByteArray();

// Constructs an array from 'data', copying 'size' bytes.
// If size is -1, it relies on strlen(data) to determine length.
QByteArray::QByteArray(const char *data, int size = -1);

// Constructs a byte array of 'size' bytes, initializing every byte to 'ch'
QByteArray::QByteArray(int size, char ch);

Data manipulation methods:

// Append data to the end
QByteArray &QByteArray::append(const QByteArray &ba);
void QByteArray::push_back(const QByteArray &other);

// Prepend data to the beginning
QByteArray &QByteArray::prepend(const QByteArray &ba);
void QByteArray::push_front(const QByteArray &other);

// Insert data at byte offset 'i' (0-based index)
QByteArray &QByteArray::insert(int i, const QByteArray &ba);

// Remove 'len' bytes starting from offset 'pos'
QByteArray &QByteArray::remove(int pos, int len);

// Remove 'n' bytes from the tail
void QByteArray::chop(int n);

// Truncate the array at position 'pos', discarding everything after it
void QByteArray::truncate(int pos);

Tags: Qt QImage QSettings QByteArray C++

Posted on Sun, 10 May 2026 14:48:13 +0000 by auddog