QCustomPlot Discussion and Comments

Legend TitleReturn to overview

I needed to add a title to the legend to indicate what is represented there. To do this I created a new subclass of QCPAbstractLegendItem that contains a string. I thought I would share in case any one else is needing the same functionality.

Usage:

	QCPStringLegendItem* pLegendItem = qobject_cast<QCPStringLegendItem*>(m_pUi->customPlot->legend->elementAt(0));
	if (nullptr != pLegendItem)
	{
		pLegendItem->setText(strLabel);
	}
	else
	{
		pLegendItem = new QCPStringLegendItem(m_pUi->customPlot->legend, strLabel);
		m_pUi->customPlot->legend->insertRow(0);
		m_pUi->customPlot->legend->addElement(0, 0, pLegendItem);
	}

Header:

class QCPStringLegendItem : public QCPAbstractLegendItem
{
  Q_OBJECT

public:
	explicit QCPStringLegendItem(QCPLegend *pParent, const QString& strText);
	
	QString text() const;
	void setText(const QString& strText);

protected:
	virtual void draw(QCPPainter *painter);
	virtual QSize minimumSizeHint() const;

private:
	QString m_strText;
};

Source:

QCPStringLegendItem::QCPStringLegendItem(QCPLegend *pParent, const QString& strText)
	: QCPAbstractLegendItem(pParent)
	, m_strText(strText)
{
}

QString QCPStringLegendItem::text() const
{
	return m_strText;
}

void QCPStringLegendItem::setText(const QString& strText)
{
	m_strText = strText;
}

void QCPStringLegendItem::draw(QCPPainter *pPainter)
{
	pPainter->setFont(mFont);
	pPainter->setPen(QPen(mTextColor));
	QRectF textRect = pPainter->fontMetrics().boundingRect(0, 0, 0, 0, Qt::TextDontClip, m_strText);
	pPainter->drawText(mRect.x() + mMargins.left(), mRect.y(), textRect.width(), textRect.height(), Qt::TextDontClip | Qt::AlignHCenter, m_strText);
}

QSize QCPStringLegendItem::minimumSizeHint() const
{
	QSize cSize(0, 0);
	QFontMetrics fontMetrics(mFont);
	QRect textRect = textRect = fontMetrics.boundingRect(0, 0, 0, 0, Qt::TextDontClip, m_strText);
	cSize.setWidth(textRect.width() + mMargins.left() + mMargins.right());
	cSize.setHeight(textRect.height() + mMargins.top() + mMargins.bottom());
	return cSize;
}

Thanks David for the code, it provided needed functionality. Hopefully it will be pulled into mainline with one small fix.

Source line 29 currently reads:

QRect textRect = textRect = fontMetrics.boundingRect(0, 0, 0, 0, Qt::TextDontClip, m_strText);

but should read:

QRect textRect = fontMetrics.boundingRect(0, 0, 0, 0, Qt::TextDontClip, m_strText);

The original version includes a superfluous textRect =.

In newer versions of QCustomPlot, the name of the size-Function has changed to minimumOuterSizeHint

I suggest as well to declare those functions with the override keyword, not virtual!

    void draw(QCPPainter *painter) override;
    QSize minimumOuterSizeHint() const override;