创建CShape类的步骤:
在Qt项目中创建一个新的静态库项目。
编写CShape类的定义。该类应该具有用于绘制不同形状的方法,例如绘制线、圆和矩形的方法。
在类的定义文件(.h)中添加 #include ,因为我们的类需要使用QPainter类来进行绘图操作。
在实现文件(.cpp)中实现每种形状的绘图方法。例如:
cpp Copy code
void CShape::drawLine(QPainter* painter, QPoint startPoint, QPoint endPoint)
{
painter->drawLine(startPoint, endPoint);
}
void CShape::drawCircle(QPainter* painter, QPoint center, int radius)
{
painter->drawEllipse(center, radius, radius);
}
void CShape::drawRect(QPainter* painter, QPoint topLeft, QPoint bottomRight)
{
painter->drawRect(QRect(topLeft, bottomRight));
}
编译静态库项目。在Qt Creator的构建菜单中选择“构建解决方案”或使用 Ctrl+Shift+B 快捷键。
将生成的静态库(.a 或 .lib 文件)拷贝到你的应用程序项目中。
在应用程序项目中,从CShape类的头文件中包含方法,以便使用库中的方法进行绘图。
示例代码:
CShape.h
cpp Copy code
#ifndef CSHAPE_H
#define CSHAPE_H
#include <QPainter>
class CShape
{
public:
static void drawLine(QPainter* painter, QPoint startPoint, QPoint endPoint);
static void drawCircle(QPainter* painter, QPoint center, int radius);
static void drawRect(QPainter* painter, QPoint topLeft, QPoint bottomRight);
};
#endif // CSHAPE_H
CShape.cpp
cpp Copy code
#include "cshape.h"
void CShape::drawLine(QPainter* painter, QPoint startPoint, QPoint endPoint)
{
painter->drawLine(startPoint, endPoint);
}
void CShape::drawCircle(QPainter* painter, QPoint center, int radius)
{
painter->drawEllipse(center, radius, radius);
}
void CShape::drawRect(QPainter* painter, QPoint topLeft, QPoint bottomRight)
{
painter->drawRect(QRect(topLeft, bottomRight));
}
调用例子:
cpp Copy code
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "cshape.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::paintEvent(QPaintEvent*)
{
QPainter painter(this);
// 绘制直线
CShape::drawLine(&painter, QPoint(10, 10), QPoint(100, 100));
// 绘制圆
CShape::drawCircle(&painter, QPoint(100, 100), 50);
// 绘制矩形
CShape::drawRect(&painter, QPoint(150, 150), QPoint(250, 200));
}