Persist QColorDialog custom colors across application restarts

Qt's QColorDialog loads custom colors from QSettings on startup but
never writes them back, so user-defined colors in the color picker
are lost when the application exits.

Save and load the 16 custom color slots explicitly via QSettings
in QETApp's constructor (after initStyle) and destructor (before
other settings are flushed). This covers every QColorDialog usage
in the application transparently.

Also fixes a QColorDialog memory leak in DiagramView.
This commit is contained in:
Kellermorph
2026-09-18 11:13:26 +02:00
parent 918756a91a
commit fa52aab149
4 changed files with 65 additions and 1 deletions
+55
View File
@@ -20,10 +20,13 @@
#include "shortcutmanager.h"
#include <limits>
#include <QBuffer>
#include <QColorDialog>
#include <QGraphicsSceneContextMenuEvent>
#include <QAction>
#include <QFileInfo>
#include <QSaveFile>
#include <QSettings>
#include <QTextStream>
#include <QRegularExpression>
#include <QActionGroup>
@@ -845,3 +848,55 @@ bool QET::writeToFile(QDomDocument &xml_doc, QFile *file, QString *error_message
return(true);
}
/**
@brief QET::saveCustomColors
Save the 16 QColorDialog custom colors to QSettings so they persist
across application restarts.
*/
void QET::saveCustomColors()
{
QByteArray ba;
QBuffer buf(&ba);
buf.open(QIODevice::WriteOnly);
QDataStream s(&buf);
s.setVersion(QDataStream::Qt_6_0);
for (int i = 0; i < 16; i++)
s << QColorDialog::customColor(i);
QSettings settings;
settings.setValue(QStringLiteral("color/customColors"), ba);
}
/**
@brief QET::loadCustomColors
Load the 16 QColorDialog custom colors from QSettings into Qt's
internal custom color array. A short or corrupt buffer is ignored
so that unread slots keep their default rather than turning black.
*/
void QET::loadCustomColors()
{
QSettings settings;
QByteArray ba = settings.value(QStringLiteral("color/customColors")).toByteArray();
// Fall back to the legacy ungrouped key used by earlier versions.
if (ba.isEmpty())
ba = settings.value(QStringLiteral("customColors")).toByteArray();
if (ba.isEmpty())
return;
QBuffer buf(&ba);
buf.open(QIODevice::ReadOnly);
QDataStream s(&buf);
s.setVersion(QDataStream::Qt_6_0);
QColor colors[16];
for (int i = 0; i < 16; i++)
s >> colors[i];
if (s.status() != QDataStream::Ok)
return;
for (int i = 0; i < 16; i++)
QColorDialog::setCustomColor(i, colors[i]);
}