用painEvent()和QPixmap()在QLabel上繪圖
阿新 • • 發佈:2019-01-24
#include ... #include ... MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); } MainWindow::~MainWindow() { delete ui; } //顯示影象,事件觸發 void MainWindow::paintEvent(QPaintEvent *) { //QPainter painter(this); QPainter painter; int labelWid=ui->shapeLabel->width(); int labelHei=ui->shapeLabel->height(); QPixmap pix(labelWid,labelHei);//定義一個新的物件,並用給定的引數構建影象 pix.fill(Qt::transparent);//透明 painter.begin(&pix); //在pix上繪圖, 附帶重置屬性 QPen pen1(Qt::red,5,Qt::DashLine,Qt::FlatCap,Qt::RoundJoin); painter.setPen(pen1); painter.drawLine(45,10,100,80);//直線 QPen pen2(Qt::green,5,Qt::DashLine,Qt::FlatCap,Qt::RoundJoin); painter.setPen(pen2); painter.drawLine(75,10,100,60); painter.end(); ui->shapeLabel->setPixmap(pix);//使用QLabel顯示pix上的繪製的影象 }