sacle_x和scale_y分别为X坐标和Y坐标的缩放因子,num_mark为x轴刻度数。最后两个参数是坐标系尺寸。
void Widget::creatCoordinates(qreal sacle_x,qreal scale_y,int num_mark,int win_width,int win_height)
{
resize(win_width,win_height);
QPainter painter(this);
int w = width(); //width of widget
int h = height(); //height of widget
(-w/2,-h/2,w,h); //set window
QPoint topleft(-w/2,-h/2); //topleft point of window
QSize size(w-1,h-1); //window size
QRect rectBoder(topleft,size); //window border rect
(rectBoder); //绘制窗口边框
(0,-h/2,0,h/2); // 绘制X轴
(-w/2,0,w/2,0); // 绘制Y轴
//绘制X轴的三角形箭头
QPoint pointsX[3] = {QPoint(w/2,0),QPoint(w/2-8,-8),QPoint(w/2-8,8)};
QBrush brush(Qt::red,Qt::SolidPattern); //画刷颜色设为红色
(brush);
(pointsX,3); //绘制三角形箭头
//绘制Y轴的三角形箭头
QPoint pointsY[3] = {QPoint(0,h/2),QPoint(-8,h/2-8),QPoint(8,h/2-8)};
(pointsY,3); //绘制多边形,此处为三边形
//绘制X轴上刻度
int stepX = w/num_mark; //X轴的刻度间隔长度,num_markX为X轴上总刻度数。
for(int i =1;i<=num_mark/2;i++)
{
( i*stepX,0, i*stepX,8);
//X轴正向刻度,箭头的边长设为8个像素
(i*stepX,0,QString::number(i*stepX));
//X轴正向刻度坐标
( -i*stepX,0, -i*stepX,8); //X轴负向刻度
(-i*stepX,0,QString::number(-i*stepX)); //X轴负向刻度坐标
}
//绘制Y轴上刻度
int num_markY = h/stepX;
int stepY = stepX;
for(int i =1;i<=num_markY/2;i++)
{
( 0,i*stepY,8,i*stepY); //Y轴正向刻度
(8,i*stepY,QString::number(i*stepY/scale_y)); //Y轴正向刻度坐标
( 0,-i*stepY,8,-i*stepY); //Y轴负向刻度
(8,-i*stepY,QString::number(-i*stepY/scale_y)); //Y轴负向刻度坐标
}
//在原点标记一个斜体字母O
QFont font("Times",14);
(true);
(font);
(0,0,"O");
}
以下是函数调用及绘制的坐标系:
void Widget::paintEvent(QPaintEvent *event)
{
creatCoordinates(1,1,20,800,600);
//scale(1,1),X轴画20个刻度,窗口尺寸800*600
}