首先我将主窗口设置为透明:
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
setWindowOpacity(1);
setWindowFlags(Qt::FramelessWindowHint);
setAttribute(Qt::WA_TranslucentBackground);
....
然后我希望在主窗口上画各种图形(直线,圆等),检测鼠标左键按下,记录第一个点位置,然后鼠标移动时可以从第一个点的位置画一条到当前位置的直线,大致代码如下:
void MainWindow::mousePressEvent(QMouseEvent *e)
{
if (e->button() == Qt::LeftButton) {
firstPnt = e->pos();
}
}
void MainWindow::mouseMoveEvent(QMouseEvent *e)
{
QPoint pnt = e->pos();
curPnt.setX(e->x());
curPnt.setY(e->y());
this->repaint(0, 0, 1920, 1080);
}
我的主窗口是1920*1080,调用repaint后会执行paintEvent:
void MainWindow::paintEvent(QPaintEvent *e)
{
QPainter painter(this);
painter.setRenderHint(QPainter::Antialiasing, true);
painter.setPen(QPen(Qt::black, 4, Qt::SolidLine, Qt::RoundCap));
painter.drawLine(firstPnt.x(), firstPnt.y(), curPnt.x(), curPnt.y());
}
但是repaint并没有把原先的图形清除掉,而且鼠标移动画图过程非常卡顿,有什么好的方法么,我才接触QT不到一星期,大佬帮帮忙。