QT设置视口-物理坐标矩形

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>

QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    MainWindow(QWidget *parent = nullptr);
    ~MainWindow();

private:
    Ui::MainWindow *ui;
protected:
    //重绘事件处理函数
    void paintEvent(QPaintEvent *event);
    void mouseMoveEvent(QMouseEvent *event);
};
#endif // MAINWINDOW_H

 

#include "mainwindow.h"
#include "./ui_mainwindow.h"
#include <QPainter> //添加QPainter,头文件。点击榔头图标进行构建--打开cpp,再关闭(QT6.3.1)
//mainwindow.cpp:6:14: Allocation of incomplete type 'Ui::MainWindow' (fix available)
//mainwindow.h:7:22: forward declaration of 'Ui::MainWindow'
//Include "ui_mainwindow.h" for symbol Ui::MainWindow
#include <QMouseEvent>
#include <QToolTip>


MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::paintEvent(QPaintEvent *event)
{
  QPainter painter2(this);
  painter2.setWindow(-50,-50,100,100);//设置逻辑坐标
  painter2.setBrush(Qt::green);
  painter2.drawRect(0,0,20,20);
  setMouseTracking(true);//不按鼠标按键也能触发鼠标移动事件

  QPainter painter3(this);
  int side=qMin(width(),height());
  int x=(width()/2);
  int y=(height()/2);
  //设置视口-物理坐标矩形

  painter3.setViewport(x,y,side,side);
  painter3.setWindow(0,0,100,100);
  painter3.setBrush(Qt::green);
  painter3.drawRect(30,0,20,20);

}

void MainWindow::mouseMoveEvent(QMouseEvent *event)
{
  QString pos=QString("%1,%2").arg(event->pos().x()).arg(event->pos().y());//获取物理坐标
  QToolTip::showText(event->globalPos(),pos,this);//点击鼠标左键,移动鼠标,显示坐标

}

 

posted @ 2022-10-27 22:01  txwtech  阅读(28)  评论(0编辑  收藏  举报