Hi,
the number of items in a Legend row is static. So if a plot is resized with a legend on top of the plot, the legend items become unreadable sooner or later. So it would be greate, if the Legend items would wrap dynamically if the plot is resized, like this happens with legend items in the Qwt plotting framework. I implement a solution that works for me. The following code will make the legend items wrap quomatically on plot resize:
//=========================================================================== int CExtendedCustomPlotPrivate::legendColumnsForWidth(int width) const { Q_Q(const CExtendedCustomPlot); int maxColumns = q->plottableCount(); if (maxLegendRowWidth(maxColumns) <= width) { return maxColumns; } for (int numColumns = 2; numColumns <= maxColumns; numColumns++ ) { const int rowWidth = maxLegendRowWidth(numColumns); if (rowWidth > width) { return numColumns - 1; } } return 1; // At least 1 column } //=========================================================================== int CExtendedCustomPlotPrivate::maxLegendRowWidth(int numColumns) const { Q_Q(const CExtendedCustomPlot); int col; QVector<int> colWidth(numColumns, 0); int ItemCount = q->plottableCount(); for (int i = 0; i < ItemCount; ++i) { col = i % numColumns; colWidth[col] = qMax(colWidth[col], legendItemWidth(i)); } int rowWidth = (numColumns - 1) * q->legend->columnSpacing(); for (col = 0; col < numColumns; ++col) { rowWidth += colWidth[col]; } return rowWidth; } //=========================================================================== int CExtendedCustomPlotPrivate::legendItemWidth(int i) const { Q_Q(const CExtendedCustomPlot); auto legend = q->legend; QCPPlottableLegendItem* Item = dynamic_cast<QCPPlottableLegendItem*>(legend->item(i)); QFontMetrics FontMetrics(Item->font()); int Width = (FontMetrics.boundingRect(Item->plottable()->name()).width() + legend->iconSize().width() + legend->iconTextPadding() + Item->margins().left() + Item->margins().right()); return Width; } //=========================================================================== void CExtendedCustomPlot::resizeEvent(QResizeEvent* event) { Q_D(CExtendedCustomPlot); Super::resizeEvent(event); updateLegendLayout(); } //=========================================================================== void CExtendedCustomPlot::updateLegendLayout() { Q_D(CExtendedCustomPlot); if (!legend) { return; } int Columns = d->legendColumnsForWidth(legend->rect().width()); legend->setWrap(Columns); legend->setFillOrder(QCPLayoutGrid::foColumnsFirst, true); }
Btw, would be great to have a GitHub repository to provide patches, improvements or fixes.