QT QPainter C++测试源代码
立即下载
资源介绍:
本C++代码用于测试QPainter的drawText函数
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include
#include
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
connect(ui->RectShowpushButton,&QPushButton::clicked,this,&MainWindow::onShowRectpushButtonClicked);
connect(ui->TextShowpushButton,&QPushButton::clicked,this,&MainWindow::onShowTextpushButtonClicked);
connect(ui->RectClearpushButton,&QPushButton::clicked,this,&MainWindow::toClearView);
connect(ui->TextClearpushButton,&QPushButton::clicked,this,&MainWindow::toClearView);
m_pPixmap=new QPixmap(800,800);
m_pPixmap->fill(Qt::white);
initView();
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::initView()
{
m_pPixmap=new QPixmap(800,800);
m_pPixmap->fill(Qt::white);
QPainter painter(m_pPixmap);
painter.translate(400,400);
QPen pen;
pen.setWidth(1); // 设置线条宽度为1像素
// 可选:设置线条颜色、样式等
pen.setColor(Qt::black); // 设置线条颜色为黑色
pen.setStyle(Qt::DashLine); // 设置线条样式为短实线
painter.setPen(pen);
painter.drawLine(0,-400,0,400);
painter.drawLine(-400,0,400,0);
painter.drawLine(100,1,100,5);
painter.drawLine(1,100,5,100);
painter.drawText(90,-2,"100");
painter.drawText(390,-2,"x");
painter.drawText(-23,105,"100");
painter.drawText(-10,395,"y");
painter.end();
ui->Viewlabel->setPixmap(*m_pPixmap);
}
void MainWindow::ShowLOG(QString log)
{
QString logs=ui->textBrowser->toPlainText();
logs=QTime::currentTime().toString("[hh:mm:ss.zzz]: ")+log+"\n"+logs;
ui->textBrowser->clear();
ui->textBrowser->setPlainText(logs);
}
void MainWindow::onShowRectpushButtonClicked()
{
QPainter painter(m_pPixmap);
painter.translate(400,400);
QPen pen;
pen.setWidth(1); // 设置线条宽度为1像素
// 可选:设置线条颜色、样式等
pen.setColor(Qt::blue); // 设置线条颜色为黑色
pen.setStyle(Qt::SolidLine); // 设置线条样式为实线
painter.setPen(pen);
painter.drawRect(ui->RectXspinBox->value(),ui->RectYspinBox->value(),
ui->RectWidthspinBox->value(),ui->RectHeightspinBox->value());
painter.end();
ui->Viewlabel->setPixmap(*m_pPixmap);
}
void MainWindow::onShowTextpushButtonClicked()
{
QFont font=ui->fontComboBox->currentFont();
font.setPointSize(ui->FontSizespinBox->value());
QFontMetrics fontMetrics(font);
QRect textRect=fontMetrics.boundingRect(ui->TextlineEdit->text());
ShowLOG("QFontMetrics result:\ntext x pos:"+QString::number(textRect.x())+
"\ntext y pos:"+QString::number(textRect.y())+
"\ntext width:"+QString::number(textRect.width())+
"\ntext height:"+QString::number(textRect.height()));
QPainter painter(m_pPixmap);
painter.translate(400,400);
QPen pen;
pen.setWidth(1); // 设置线条宽度为1像素
// 可选:设置线条颜色、样式等
pen.setColor(Qt::red); // 设置线条颜色为黑色
pen.setStyle(Qt::SolidLine); // 设置线条样式为实线
painter.setPen(pen);
painter.setFont(font);
painter.drawText(ui->TextXspinBox->value(),ui->TextYspinBox->value(),ui->TextlineEdit->text());
painter.end();
ui->Viewlabel->setPixmap(*m_pPixmap);
}
void MainWindow::toClearView()
{
initView();
}