Qt 卡片控件 一个以卡片样式展示信息的自定义控件

Qt 卡片控件 一个以卡片样式展示信息的自定义控件

效果图:
Qt 卡片控件 一个以卡片样式展示信息的自定义控件_第1张图片

代码:

MyCardWidget:

#pragma once

#include 
#include "ui_MyCardWidget.h"
#include "MyHeaders.h"
class MyCardWidget : public QWidget
{
	Q_OBJECT

public:
	MyCardWidget(QWidget *parent = Q_NULLPTR);
	~MyCardWidget();
	void setHeards(const QStringList& strs);
	void setBottoms(const QStringList& strs);
	void setPixmap(const QPixmap& pix);

protected:
	virtual void paintEvent(QPaintEvent* event);
private:
	Ui::MyCardWidget ui;
	QStringList m_headList;
	QStringList m_bottomList;
	QPixmap m_nikPix;

};

MyCardWidget.cpp:

#include "MyCardWidget.h"
#include 
#if _MSC_VER>=1600
#pragma execution_character_set("utf-8")
#endif
MyCardWidget::MyCardWidget(QWidget *parent)
	: QWidget(parent)
{
	ui.setupUi(this);
	//隐藏标题栏
	setWindowFlags(Qt::SubWindow | Qt::FramelessWindowHint);
	setMouseTracking(true);
	//resize(100, 100);
}

MyCardWidget::~MyCardWidget()
{
}

void MyCardWidget::setHeards(const QStringList& strs)
{
	m_headList = strs;
}

void MyCardWidget::setBottoms(const QStringList& strs)
{
	m_bottomList = strs;
}

void MyCardWidget::setPixmap(const QPixmap& pix)
{
	m_nikPix = pix;
}

void MyCardWidget::paintEvent(QPaintEvent* event)
{
	QPainter painter(this);
	int width = this->width();
	painter.save();
	{
		
		int color = qrand() % 20;
		QBrush brush(QGradient(static_cast<QGradient::Preset>(color)));
		painter.setBrush(brush); 
	}
	QRect headTextRect = QRect(QPoint(0, 0), QPoint(width, 190));
	//订单信息栏
	painter.drawRect(headTextRect);

	QRect headTextRR(QPoint(10, 10), QPoint(width-10, 190-10));
	painter.restore();
	painter.save();
	QPen headPen;
	//headPen.setColor(Qt::white);
	//headPen.setWidthF(15.0);
	painter.setFont(QFont("宋体", 20, 1));
	painter.drawText(headTextRR, Qt::AlignCenter, m_headList.join("\n"));
	painter.restore();
	QRect nikPix(QPoint(0,190), QPoint(60,height()));
	painter.drawPixmap(nikPix, m_nikPix);
	//头像栏
	//painter.drawRect(QRect(QPoint(60, 190), QPoint(width, height())));
	{
		int color = qrand() % 20;
		QBrush brush(QGradient(static_cast<QGradient::Preset>(color)));
		painter.setBrush(brush);
	}
	//最后信息栏
	painter.drawRect(QRect(QPoint(60, 190), QPoint(width, height())));
	painter.restore();
	painter.setFont(QFont("宋体", 15, 1));
	QRect bottomRect(QRect(QPoint(70, 200), QPoint(width - 10, height() - 10)));
	painter.drawText(bottomRect, Qt::AlignCenter, m_bottomList.join("\t"));
}

使用样例:

	MyCardWidget myCard;
	QStringList heardes = QStringList() << "a" << "b" << "c" << "d" << "e";
	QStringList bottoms = QStringList() << "a" << "b" << "c";
	myCard.setHeards(heardes);
	myCard.setBottoms(bottoms);
	QPixmap pix(":/shop/image/shop/地址.png");
	myCard.setPixmap(pix);
	myCard.show();

你可能感兴趣的:(C++与Qt开发专栏,qt,ui,开发语言)