绘制简单图形——QPainter
QPainter实现鼠标绘制简单的图形(点、直线、圆、矩形):
选择相应的图形按钮,鼠标点击左键开始绘制,松开鼠标完成绘制。
1.Mainwindow.h文件的相关声明
private: QPixmap pix;//画布 QPoint lastpoint,endpoint;//存放鼠标坐标 QCursor cursor; //设置默认光标 QPushButton *line,*point,*circle,*rect;//图形选择按钮 bool isline=false,ispoint=false,iscircle=false,isrect=false;//绘图标志 private slots: void initialization();//坐标初始化 void Point();
void Line(); void Circle();
void Rect(); protected: void paintEvent(QPaintEvent *); void mousePressEvent(QMouseEvent *event); void mouseReleaseEvent(QMouseEvent *event); void mouseMoveEvent(QMouseEvent *event);
2.Mainwindow.cpp文件
pix=QPixmap(600,600);//设置画布大小
pix.fill(Qt::lightGray);//画布颜色
line=new QPushButton("线",this);
point=new QPushButton("点",this);
circle=new QPushButton("圆",this);
rect=new QPushButton("矩形",this);
point->setGeometry(700,90,50,30);
line->setGeometry(700,130,50,30);
circle->setGeometry(700,170,50,30);
rect->setGeometry(700,210,50,30);
connect(line,&QPushButton::clicked,this,&MainWindow2::Line);
connect(point,&QPushButton::clicked,this,&MainWindow2::Point);
connect(circle,SIGNAL(released()),this,SLOT(Circle()));
connect(rect,SIGNAL(released()),this,SLOT(Rect()));
(1)paintEvent:
void MainWindow::paintEvent(QPaintEvent *)
{
QPainter paint(&pix);
QPen pen;
pen.setColor(Qt::darkCyan);
pen.setWidth(1);
paint.setPen(pen);
if(isline==true){
if(endpoint.x()-lastpoint.x()!=0 || endpoint.y()-lastpoint.y()!=0)//排除绘制点的可能性
paint.drawLine(lastpoint,endpoint);
this->initialization();
}
if(ispoint==true){
paint.drawPoint(lastpoint); this->initialization();
}
if(iscircle==true){
qreal r=sqrt(pow((endpoint.x()-lastpoint.x()),2)+pow((endpoint.y()-lastpoint.y()),2));
paint.drawEllipse(lastpoint.x()-r,lastpoint.y()-r,2*r,2*r);
this->initialization();
}
if(isrect==true){
qreal width=endpoint.x()-lastpoint.x();
qreal height=endpoint.y()-lastpoint.y();
if(width!=0 && height!=0){
paint.drawRect(lastpoint.x(),lastpoint.y(),width,height);
this->initialization();
}
}
QPainter painter(this);
painter.drawPixmap(0,0,pix);
}
(2)按钮的点击事件:
void MainWindow::Line(){
isline=true;
ispoint=iscircle=isrect=false;
}
void MainWindow::Point(){
ispoint=true;
isline=iscircle=isrect=false;
}
void MainWindow::Circle(){
iscircle=true;
ispoint=isline=isrect=false;
}
void MainWindow::Rect(){
isrect=true;
ispoint=iscircle=isline=false;
}
(3)鼠标事件
void MainWindow::mousePressEvent(QMouseEvent *event)
{
if(isline==true||ispoint==true||iscircle==true||isrect==true){
//按下左键,改变光标为十字形状
QCursor c1;
c1.setShape(Qt::CrossCursor);
setCursor(c1);
if(event->button()==Qt::LeftButton){
lastpoint=event->pos();qDebug()<<lastpoint;
}
endpoint=lastpoint;
}
}
void MainWindow::mouseMoveEvent(QMouseEvent *event)
{
if(event->button()&Qt::LeftButton){
endpoint=event->pos();
update();
}
}
void MainWindow::mouseReleaseEvent(QMouseEvent *event)
{
if(isline==true||ispoint==true||iscircle==true||isrect==true){
if(event->button()==Qt::LeftButton){
endpoint=event->pos();
update();
}
setCursor(cursor);//完成绘制后,恢复光标形状
}
}