Commit 94bafcf3 authored by Arjen Hiemstra's avatar Arjen Hiemstra
Browse files

Add a method to Formatter for getting the maximum length of a unit

So we can use it to determine how much space a given value can take as
maximum.
parent 0a6d5cbf
......@@ -24,6 +24,7 @@ add_library(KSysGuard::Formatter ALIAS Formatter)
target_link_libraries(Formatter
PUBLIC
Qt::Core
Qt::Gui
PRIVATE
KF5::I18n
)
......
......@@ -26,6 +26,7 @@
#include <QLocale>
#include <QTime>
#include <QFontMetrics>
#include <cmath>
......@@ -394,4 +395,30 @@ QString Formatter::symbol(Unit unit)
}
}
qreal Formatter::maximumLength(Unit unit, const QFont &font)
{
auto order = unitOrder(unit);
QString maximum;
switch (unitBase(unit)) {
case UnitByte:
maximum = formatValue(order - 0.5, UnitMegaByte, MetricPrefixMega);
break;
case UnitByteRate:
maximum = formatValue(order - 0.5, UnitMegaByteRate, MetricPrefixMega);
break;
case UnitHertz:
maximum = formatValue(order - 0.5, UnitMegaHertz, MetricPrefixMega);
break;
case UnitPercent:
maximum = formatValue(9999.9, UnitPercent);
break;
default:
return -1.0;
}
auto metrics = QFontMetrics{font};
return metrics.horizontalAdvance(maximum);
}
} // namespace KSysGuard
......@@ -89,6 +89,14 @@ public:
* The returned unit symbol is localized.
*/
static QString symbol(Unit unit);
/**
* Return the maximum length of a formatted string for the specified unit and font.
*
* @param unit The unit to use.
* @param font The font to use.
*/
static qreal maximumLength(Unit unit, const QFont &font);
};
} // namespace KSysGuard
......
......@@ -33,4 +33,9 @@ QString FormatterWrapper::formatValueShowNull(const QVariant &value, KSysGuard::
return Formatter::formatValue(value, unit, targetPrefix, FormatOptionShowNull);
}
qreal KSysGuard::FormatterWrapper::maximumLength(KSysGuard::Unit unit, const QFont &font)
{
return Formatter::maximumLength(unit, font);
}
}
......@@ -49,6 +49,8 @@ public:
Q_INVOKABLE QString formatValueShowNull(const QVariant &value, KSysGuard::Unit unit,
KSysGuard::MetricPrefix targetPrefix = MetricPrefixAutoAdjust
);
Q_INVOKABLE qreal maximumLength(KSysGuard::Unit unit, const QFont &font);
};
}
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment