绘制图例(颜色+文本)

QT

Posted by YiMiTuMi on July 16, 2025

图例

继承QWidget绘制每一个图例项,颜色 + 文本。

class LegendItem : public QWidget
{

public:
	LegendItem (const QColor& color, const QString& text, QWidget* parent = nullptr) : QWidget(parent)
	{
		m_color = color;
		m_text = text;

		setFixedHeight(25);
	}

protected:

	void paintEvent() override
	{
		//绘制矩形
		QPainter painte(this);
		painte.setRenderHint(Qt::NoPen);
		painte.drawRoundRect(6, 6, 15, 15);

		//绘制文本
		painte.serPen(Qt::white);
		painte.serFont(QFont("Arial", 10));
		painte.drawText(35, 17, m_text);
	}

private:
	
	QColor m_color;
	QString m_text;
};

将绘制好的每一个图例项绘制到一个QWidget中用于显示。

//图例类
calss TransparentLegend : public QWidget
{
	
public:

	TransparentLegend (QWidget* parent = nullptr) : QWidget(parent)
	{
		setStyleSheet("background:transparent; border-radius: 8px;");
		setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);

		QVBoxLayout* layout = new QVBoxLayout(this);
		layout->setContentsMargins(10, 10, 10, 10);
		layout->setSpacing(5);


		//添加项
		layout->addWidget(new LegendItem(QColor(255, 255, 0), "1"));
		layout->addWidget(new LegendItem(QColor(0, 255, 255), "2"));
		layout->addWidget(new LegendItem(QColor(0, 255, 0), "3"));
		layout->addWidget(new LegendItem(QColor(0, 0, 255), "4"));

		
		setLayout(layout);

	}	
};

在QMainWindow中使用。

//初始化
void xxx::InitLegend()
{
	m_pLegend = new TransparentLegend(this);
	m_pLegend->resize(200, 200);
	m_pLegend->show();

	//用于更新位置
	UpDataLegendPosition();	
}

void xxx::UpDataLegendPosition()
{
	if (m_pLegend == nullptr)
	{
		return;
	}

	int margin = 10; //边距
	
	int x = margin;
	int y = this->height() - m_pLegend->height();

	m_pLegend->move(x, y);
}