精华内容
下载资源
问答
  • #endif // GRAPHICSRECTITEM_H graphicsview.h #ifndef GRAPHICSVIEW_H #define GRAPHICSVIEW_H #include #include #include class GraphicsView : public QGraphicsView { Q_OBJECT public: GraphicsView(QWidget ...

     graphicsrectitem.h

    #ifndef GRAPHICSRECTITEM_H
    #define GRAPHICSRECTITEM_H
    
    #include <QGraphicsItem>
    #include "sizehandlerect.h"
    
    class GraphicsRectItem : public QGraphicsItem
    {
    public:
        GraphicsRectItem(const QRect & rect ,QGraphicsItem * parent);
    
        QRectF boundingRect() const;
        virtual void resizeTo(SizeHandleRect::Direction dir, const QPointF & point );
        void move(const QPointF & point);
        virtual Qt::CursorShape getCursor(SizeHandleRect::Direction dir );
        SizeHandleRect::Direction  hitTest( const QPointF & point ) const;
        virtual QRectF  rect() const;
        virtual void updateGeometry();
        QRectF m_rect;
    
    private:
    
        typedef QVector<SizeHandleRect*> Handles;
        Handles m_handles;
        int selection_handle_size = 4;
    
    protected:
        void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget);
    
        void setState(SelectionHandleState st);
        QVariant itemChange(GraphicsItemChange change, const QVariant &value);
    };
    
    #endif // GRAPHICSRECTITEM_H
    

    graphicsscene.h

    #ifndef GRAPHICSRECTITEM_H
    #define GRAPHICSRECTITEM_H
    
    #include <QGraphicsItem>
    #include "sizehandlerect.h"
    
    class GraphicsRectItem : public QGraphicsItem
    {
    public:
        GraphicsRectItem(const QRect & rect ,QGraphicsItem * parent);
    
        QRectF boundingRect() const;
        virtual void resizeTo(SizeHandleRect::Direction dir, const QPointF & point );
        void move(const QPointF & point);
        virtual Qt::CursorShape getCursor(SizeHandleRect::Direction dir );
        SizeHandleRect::Direction  hitTest( const QPointF & point ) const;
        virtual QRectF  rect() const;
        virtual void updateGeometry();
        QRectF m_rect;
    
    private:
    
        typedef QVector<SizeHandleRect*> Handles;
        Handles m_handles;
        int selection_handle_size = 4;
    
    protected:
        void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget);
    
        void setState(SelectionHandleState st);
        QVariant itemChange(GraphicsItemChange change, const QVariant &value);
    };
    
    #endif // GRAPHICSRECTITEM_H
    

    graphicsview.h

    #ifndef GRAPHICSVIEW_H
    #define GRAPHICSVIEW_H
    
    #include <QGraphicsView>
    #include <QKeyEvent>
    #include <QWheelEvent>
    
    class GraphicsView : public QGraphicsView
    {
        Q_OBJECT
    
    public:
        GraphicsView(QWidget *parent = 0);
    
    protected:
        void keyPressEvent(QKeyEvent *event);
        void wheelEvent(QWheelEvent *event);
    };
    
    #endif // GRAPHICSVIEW_H
    

    sizehandlerec.h

    #ifndef SIZEHANDLERECT_H
    #define SIZEHANDLERECT_H
    
    #include <QGraphicsRectItem>
    
    enum SelectionHandleState { SelectionHandleOff, SelectionHandleInactive, SelectionHandleActive };
    
    class SizeHandleRect : public QGraphicsRectItem
    {
    public:
        enum Direction { LeftTop , Top, RightTop, Right, RightBottom, Bottom, LeftBottom, Left , Center, None};
        SizeHandleRect(QGraphicsItem* parent , QRectF rect, Direction dir);
        Direction dir() const;
        bool hitTest( const QPointF & point );
        void move(qreal x, qreal y );
        void setState(SelectionHandleState st);
    protected:
        void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget);
    private:
        const Direction m_dir;
        SelectionHandleState m_state;
    };
    
    #endif // SIZEHANDLERECT_H
    

    mainwindow.h

    #ifndef MAINWINDOW_H
    #define MAINWINDOW_H
    
    #include <QMainWindow>
    
    #include "GraphicsRect/graphicsscene.h"
    #include "GraphicsRect/graphicsview.h"
    
    namespace Ui {
    class MainWindow;
    }
    
    class MainWindow : public QMainWindow
    {
        Q_OBJECT
    
    public:
        explicit MainWindow(QWidget *parent = 0);
        ~MainWindow();
    
    private slots:
        void on_pushButton_createRect_clicked();
    
        void on_pushButton_getRect_clicked();
    
        void on_pushButton_addPix_clicked();
    
    private:
        Ui::MainWindow *ui;
        GraphicsScene *scene = NULL;
    };
    
    #endif // MAINWINDOW_H
    


    下面是资源文件

    graphicsrectitem.cpp

    #include "graphicsrectitem.h"
    #include <QPen>
    #include <QPainter>
    #include <QDebug>
    
    GraphicsRectItem::GraphicsRectItem(const QRect &rect, QGraphicsItem *parent) :
        QGraphicsItem(parent)
    {
        m_rect = rect;
        m_handles.reserve(SizeHandleRect::None);
        for (int i = SizeHandleRect::LeftTop; i <= SizeHandleRect::Left; ++i) {
            SizeHandleRect *shr = new SizeHandleRect(this, QRectF(0,0,1,1), static_cast<SizeHandleRect::Direction>(i));
            m_handles.push_back(shr);
        }
        updateGeometry();
        setFlag(QGraphicsItem::ItemIsMovable, true);
        setFlag(QGraphicsItem::ItemIsSelectable, true);
        setFlag(QGraphicsItem::ItemSendsGeometryChanges, true);
        this->setAcceptHoverEvents(true);
    }
    
    void GraphicsRectItem::resizeTo(SizeHandleRect::Direction dir, const QPointF &point)
    {
        QPointF local = mapFromScene(point);
        QString dirName;
    
        QRect delta =m_rect.toRect();
        switch (dir) {
        case SizeHandleRect::LeftTop:
            delta.setTopLeft(local.toPoint());
    
            break;
        case SizeHandleRect::Top:
            dirName = "Top";
            delta.setTop(local.y());
            break;
    
        case SizeHandleRect::RightTop:
            dirName = "RightTop";
            delta.setTopRight(local.toPoint());
            break;
    
        case SizeHandleRect::Left:
            dirName = "Left";
            delta.setLeft(local.x());
            break;
        case SizeHandleRect::Right:
            dirName = "Rigth";
            delta.setRight(local.x());
            break;
    
        case SizeHandleRect::LeftBottom:
            dirName = "LeftBottom";
            delta.setBottomLeft(local.toPoint());
            break;
    
        case SizeHandleRect::Bottom:
            dirName = "Bottom";
            delta.setBottom(local.y());
            break;
    
        case SizeHandleRect::RightBottom:
            dirName = "RightBottom";
            delta.setBottomRight(local.toPoint());
            break;
    
        default:
            break;
        }
        prepareGeometryChange();
    //    if(m_isSquare)
    //    {
    //        delta.setHeight(delta.width());
    //    }
        m_rect =delta;
        updateGeometry();
    }
    
    void GraphicsRectItem::move(const QPointF &point)
    {
        QPointF local = mapFromScene(point);
    
        QRectF delta = QRectF(local, m_rect.size());
    
        prepareGeometryChange();
        m_rect =delta;
        updateGeometry();
    }
    
    Qt::CursorShape GraphicsRectItem::getCursor(SizeHandleRect::Direction dir)
    {
        switch (dir) {
        case SizeHandleRect::Right:
            return Qt::SizeHorCursor;
        case SizeHandleRect::RightTop:
            return Qt::SizeBDiagCursor;
        case SizeHandleRect::RightBottom:
            return Qt::SizeFDiagCursor;
        case SizeHandleRect::LeftBottom:
            return Qt::SizeBDiagCursor;
        case SizeHandleRect::Bottom:
            return Qt::SizeVerCursor;
        case SizeHandleRect::LeftTop:
            return Qt::SizeFDiagCursor;
        case SizeHandleRect::Left:
            return Qt::SizeHorCursor;
        case SizeHandleRect::Top:
            return Qt::SizeVerCursor;
        default:
            break;
        }
        return Qt::ArrowCursor;
    }
    
    SizeHandleRect::Direction GraphicsRectItem::hitTest(const QPointF &point) const
    {
        const Handles::const_iterator hend =  m_handles.end();
        for (Handles::const_iterator it = m_handles.begin(); it != hend; ++it)
        {
            if ((*it)->hitTest(point) ){
                return (*it)->dir();
            }
        }
        return SizeHandleRect::None;
    }
    
    void GraphicsRectItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
    {
        QPen pen =painter->pen();
        pen.setWidth(4);
        pen.setColor(QColor(255, 0, 0));
        painter->setPen(pen);
        painter->drawRect(rect());
    }
    
    void GraphicsRectItem::updateGeometry()
    {
        const QRectF &rect = this->boundingRect();
    
        const Handles::iterator hend =  m_handles.end();
        for (Handles::iterator it = m_handles.begin(); it != hend; ++it) {
            SizeHandleRect *hndl = *it;;
            switch (hndl->dir()) {
            case SizeHandleRect::LeftTop:
                hndl->move(rect.x() - selection_handle_size / 2, rect.y() - selection_handle_size / 2);
                break;
            case SizeHandleRect::Top:
                hndl->move(rect.x() + rect.width() / 2 - selection_handle_size / 2, rect.y() - selection_handle_size / 2);
                break;
            case SizeHandleRect::RightTop:
                hndl->move(rect.x() + rect.width() - selection_handle_size / 2, rect.y() - selection_handle_size / 2);
                break;
            case SizeHandleRect::Right:
                hndl->move(rect.x() + rect.width() - selection_handle_size / 2, rect.y() + rect.height() / 2 - selection_handle_size / 2);
                break;
            case SizeHandleRect::RightBottom:
                hndl->move(rect.x() + rect.width() - selection_handle_size / 2, rect.y() + rect.height() - selection_handle_size / 2);
                break;
            case SizeHandleRect::Bottom:
                hndl->move(rect.x() + rect.width() / 2 - selection_handle_size / 2, rect.y() + rect.height() - selection_handle_size / 2);
                break;
            case SizeHandleRect::LeftBottom:
                hndl->move(rect.x() - selection_handle_size / 2, rect.y() + rect.height() - selection_handle_size / 2);
                break;
            case SizeHandleRect::Left:
                hndl->move(rect.x() - selection_handle_size / 2, rect.y() + rect.height() / 2 - selection_handle_size / 2);
                break;
            case SizeHandleRect::Center:
                hndl->move(rect.center().x()  - selection_handle_size / 2 , rect.center().y() - selection_handle_size / 2);
                break;
            default:
                break;
            }
        }
    }
    
    QRectF GraphicsRectItem::rect() const
    {
        return QRectF(QPointF(m_rect.left(),m_rect.top()),
                      QPointF(m_rect.right(), m_rect.bottom()));
    }
    
    void GraphicsRectItem::setState(SelectionHandleState st)
    {
        const Handles::iterator hend =  m_handles.end();
        for (Handles::iterator it = m_handles.begin(); it != hend; ++it)
            (*it)->setState(st);
    }
    
    QVariant GraphicsRectItem::itemChange(QGraphicsItem::GraphicsItemChange change, const QVariant &value)
    {
        if ( change == QGraphicsItem::ItemSelectedHasChanged ) {
            qDebug()<<" Item Selected : " << value.toString();
            setState(value.toBool() ? SelectionHandleActive : SelectionHandleOff);
        }else if ( change == QGraphicsItem::ItemRotationHasChanged ){
            qDebug()<<"Item Rotation Changed:" << value.toString();
        }else if ( change == QGraphicsItem::ItemTransformOriginPointHasChanged ){
            qDebug()<<"ItemTransformOriginPointHasChanged:" << value.toPointF();
        }
        return value;
    }
    
    QRectF GraphicsRectItem::boundingRect() const
    {
        return rect();
    }
    

    graphicsscene.cpp

    #include "graphicsscene.h"
    #include <QGraphicsView>
    #include <QDebug>
    
    enum SelectMode
    {
        none,
        netSelect,
        move, //移动
        size, //改变大小
        rotate //反转
    };
    
    SelectMode selectMode = none;
    
    SizeHandleRect::Direction nDragHandle = SizeHandleRect::None;
    
    GraphicsScene::GraphicsScene()
    {
    
    }
    
    void GraphicsScene::creatRect()
    {
    //    if(m_RectItem){
    //        return;
    //    }
        this->clearSelection();
        m_RectItem = new GraphicsRectItem(QRect(0, 0, 200, 100), NULL);
        this->addItem(m_RectItem);
        m_RectItem->setSelected(true);
        this->update();
    }
    
    void GraphicsScene::SetBackGroundImage(QPixmap pix, int width, int height)
    {
        this->clear();
        QGraphicsPixmapItem* _backGroundItem= this->addPixmap(pix);
    
        qreal scale = 0.0;
        if((double)width/height > (double)pix.width()/pix.height()){
            scale = (double)height/pix.height();
        } else{
            scale = (double)width/pix.width();
        }
    
        _backGroundItem->setScale(scale);
    
    //    _backGroundItem->setPos(0,0);
    }
    
    void GraphicsScene::setCursor(const QCursor &cursor)
    {
        QList<QGraphicsView*> views  = this->views();
        if ( views.count() > 0 ){
            QGraphicsView * view = views.first();
            view->setCursor(cursor);
        }
    }
    
    void GraphicsScene::mousePressEvent(QGraphicsSceneMouseEvent *event)
    {
        QList<QGraphicsItem *> items = this->selectedItems();
        GraphicsRectItem *item = 0;
        if ( items.count() == 1 )
        {
            item = qgraphicsitem_cast<GraphicsRectItem*>(items.first());
    
            nDragHandle = item->hitTest(event->scenePos());
            if ( nDragHandle !=SizeHandleRect::None)
                selectMode = size;
            else
                selectMode =  move;
        }
        if(selectMode == move || selectMode == none){
            QGraphicsScene::mousePressEvent(event);
        }
    }
    
    void GraphicsScene::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
    {
        QList<QGraphicsItem *> items = this->selectedItems();
        if(items.count() == 1){
            GraphicsRectItem *item = qgraphicsitem_cast<GraphicsRectItem*>(items.first());
            if ( nDragHandle != SizeHandleRect::None && selectMode == size ){
                item->resizeTo(nDragHandle,event->scenePos());
            }
            else if(nDragHandle == SizeHandleRect::None && selectMode == none ){
    
    
                SizeHandleRect::Direction handle = item->hitTest(event->scenePos());
                if ( handle != SizeHandleRect::None){
                    setCursor(item->getCursor(handle));
                }else{
                    setCursor(Qt::ArrowCursor);
                }
            }
            else if(nDragHandle == SizeHandleRect::None && selectMode == move ){
    
                item->move(event->scenePos());
            }
        }
    
        this->update();
    }
    
    void GraphicsScene::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
    {
        setCursor(Qt::ArrowCursor);
        selectMode = none;
        nDragHandle = SizeHandleRect::None;
        QGraphicsScene::mouseReleaseEvent(event);
    }
    

    graphicsview.cpp

    #include "graphicsview.h"
    
    GraphicsView::GraphicsView(QWidget *parent) :
        QGraphicsView(parent)
    {
        this->setTransformationAnchor(QGraphicsView::AnchorUnderMouse);
        this->setResizeAnchor(QGraphicsView::AnchorUnderMouse);
    }
    
    void GraphicsView::keyPressEvent(QKeyEvent *event)
    {
        switch (event->key())
        {
        case Qt::Key_Plus :
            scale(1.2, 1.2);
            break;
        case Qt::Key_Minus :
            scale(1 / 1.2, 1 / 1.2);
            break;
        case Qt::Key_Right :
            rotate(30);
            break;
        }
        QGraphicsView::keyPressEvent(event);
    }
    
    void GraphicsView::wheelEvent(QWheelEvent *event)
    {
        // 滚轮的滚动量
        QPoint scrollAmount = event->angleDelta();
        // 正值表示滚轮远离使用者(放大),负值表示朝向使用者(缩小)
        scrollAmount.y() > 0 ? scale(1.2, 1.2) : scale(1 / 1.2, 1 / 1.2);
    }
    

    sizehandlerect.cpp

    #include "sizehandlerect.h"
    #include <QPainter>
    
    SizeHandleRect::SizeHandleRect(QGraphicsItem *parent, QRectF rect, Direction dir) :
        QGraphicsRectItem(rect, parent),
        m_dir(dir),
        m_state(SelectionHandleOff)
    {
        setParentItem(parent);
        hide();
    }
    
    SizeHandleRect::Direction SizeHandleRect::dir() const
    {
        return m_dir;
    }
    
    bool SizeHandleRect::hitTest(const QPointF &point)
    {
        QPointF pt = mapFromScene(point);
        return rect().contains(pt);
    }
    
    void SizeHandleRect::move(qreal x, qreal y)
    {
        setPos(x,y);
    }
    
    void SizeHandleRect::setState(SelectionHandleState st)
    {
        if (st == m_state)
            return;
        switch (st) {
        case SelectionHandleOff:
            hide();
            break;
        case SelectionHandleInactive:
        case SelectionHandleActive:
            show();
            break;
        }
        m_state = st;
    }
    
    void SizeHandleRect::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
    {
        QColor c = QColor("limegreen");
      //  c.setAlpha(200);
        painter->setPen(Qt::NoPen);
        painter->setBrush(QBrush(c));
    
        painter->drawRect(rect());
    }
    

    mainwindow.cpp

    #include "mainwindow.h"
    #include "ui_mainwindow.h"
    #include <QDebug>
    
    MainWindow::MainWindow(QWidget *parent) :
        QMainWindow(parent),
        ui(new Ui::MainWindow)
    {
        ui->setupUi(this);
        scene = new GraphicsScene();
    
        ui->graphicsView->setScene(scene);
        scene->addItem(new GraphicsRectItem(QRect(-1, -1, 3, 3), NULL));
    }
    
    MainWindow::~MainWindow()
    {
        delete ui;
    }
    
    void MainWindow::on_pushButton_createRect_clicked()
    {
        scene->creatRect();
    }
    
    void MainWindow::on_pushButton_getRect_clicked()
    {
    
        if(scene->m_RectItem){
    //        QPoint point = scene->m_RectItem->m_rect.topLeft();
            QRect rect = scene->m_RectItem->rect().toRect();
            ui->lineEdit->setText("x:" + QString::number(rect.topLeft().x()) + "  y:" + QString::number(rect.topLeft().y())
                                  + "  w:" + QString::number(rect.width()) + "  h:" + QString::number(rect.height()));
    
        }
    }
    
    void MainWindow::on_pushButton_addPix_clicked()
    {
        QPixmap pix("D:/imageprocess/111111111GraphicsRectDemo/img.bmp");
    //    QPixmap pix("img.jpg");
        scene->SetBackGroundImage(pix, ui->graphicsView->width(), ui->graphicsView->height());
    }
    

    展开全文
  • 之前出现GraphicsView画图会出现的问题做了改进,去掉边框以及对位置进行了判断 from PyQt5 import QtCore, QtGui, QtWidgets import sys from PyQt5.QtCore import * from PyQt5.QtWidgets import * from PyQt5 ...

    之前出现GraphicsView画图会出现的问题做了改进,去掉边框以及对位置进行了判断

    from PyQt5 import QtCore, QtGui, QtWidgets
    import sys
    from PyQt5.QtCore import *
    from PyQt5.QtWidgets import *
    from PyQt5 import QtWidgets
    from PyQt5 import QtGui
    
    
    class GraphicsView(QtWidgets.QGraphicsView):
        def __init__(self, parent=None):
            super(GraphicsView, self).__init__(parent)
            self.wid = 1100
            self.heit = 600
            self.setFixedSize(self.wid,self.heit)
            self.setScene(QtWidgets.QGraphicsScene(self))
            self.pixmapItem = (
                QtWidgets.QGraphicsPixmapItem()
            )  # check if everytime you open a new image the old image is still an item
            self.scene().addItem(self.pixmapItem)
            # self.scene().setSceneRect()
            self._path_item = None
            self.img = None
            self.filename = ""
            self.setFrameStyle(QFrame.NoFrame)
    
        def initial_path(self):
            self._path = QtGui.QPainterPath()
            pen = QtGui.QPen(
                QtGui.QColor("red"), 1.5, QtCore.Qt.SolidLine, QtCore.Qt.RoundCap
            )
            self._path_item = self.scene().addPath(self._path, pen)
    
        @QtCore.pyqtSlot()
        def setImage(self):
            self.filename, _ = QtWidgets.QFileDialog.getOpenFileName(
                None, "select Image", "", "Image Files (*.png *.jpg *jpg *.bmp)"
            )
            if self.filename:
                pixmap1 = QtGui.QPixmap(self.filename)
                self.pixmapItem.setPixmap(pixmap1)
    
        def mousePressEvent(self, event):
            start = event.pos()
            if (
                    not self.pixmapItem.pixmap().isNull()
                    and event.buttons() & QtCore.Qt.LeftButton
            ):
                self.initial_path()
                self._path.moveTo(self.mapToScene(start))
                self._path_item.setPath(self._path)
            super(GraphicsView, self).mousePressEvent(event)
    
        def mouseMoveEvent(self, event):
            if (
                    not self.pixmapItem.pixmap().isNull()
                    and event.buttons() & QtCore.Qt.LeftButton
                    and self._path_item is not None
            ):
    
                x = event.x()
                if x < 1:
                    x = 1
                if x > self.wid-1:
                    x = self.wid-1
                y=event.y()
                if y<1:
                    y=1
                if y > self.heit-1:
                    y = self.heit-1
                pos = QPoint(x,y)
                # self._path.lineTo(self.mapToScene(event.pos()))
                self._path.lineTo(self.mapToScene(pos))
                self._path_item.setPath(self._path)
            super(GraphicsView, self).mouseMoveEvent(event)
    
        def mouseReleaseEvent(self, event):
            x = event.x()
            if x < 1:
                x = 1
            if x > self.wid - 1:
                x = self.wid - 1
            y = event.y()
            if y < 1:
                y = 1
            if y > self.heit - 1:
                y = self.heit - 1
            end = QPoint(x, y)
            if (
                    not self.pixmapItem.pixmap().isNull()
                    and self._path_item is not None
            ):
                self._path.lineTo(self.mapToScene(end))
                self._path.closeSubpath()
                self._path_item.setPath(self._path)
                self._path_item.setBrush(QtGui.QBrush(QtGui.QColor("red")))
                # self._path_item.setFlag(
                #     QtWidgets.QGraphicsItem.ItemIsSelectable, True
                # )
                self._path_item = None
    
            super(GraphicsView, self).mouseReleaseEvent(event)
    
        def save(self):
            rect = self.scene().sceneRect()
            self.img = QtGui.QImage(rect.width(), rect.height(), QtGui.QImage.Format_RGB666)
            painter = QtGui.QPainter(self.img)
            rectf = QRectF(0, 0, self.img.rect().width(), self.img.rect().height())
            self.scene().render(painter, rectf, rect)
            filename, _ = QtWidgets.QFileDialog.getSaveFileName(
                None,"save Image", self.filename,"Image Files (*.png)"
            )
            if filename:
                self.img.save(filename)
    
    
    if __name__ == "__main__":
        app = QtWidgets.QApplication(sys.argv)
        w = QWidget()
        btnSave = QPushButton("Save image")
        view = GraphicsView()
        view.setImage()
        w.setLayout(QVBoxLayout())
        w.layout().addWidget(btnSave)
        w.layout().addWidget(view)
        btnSave.clicked.connect(lambda: view.save())
        w.show()
        sys.exit(app.exec_())
    
    
    
    展开全文
  • graphicsView->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); ui->graphicsView->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); python3 self.setVerticalScrollBarPolicy(Qt....

    c++

    ui->graphicsView->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    ui->graphicsView->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    

    python3

    self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)       # 关闭垂直滚动条
    self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)     # 关闭水平滚动条
    
    展开全文
  • qt graphics view 坐标系

    千次阅读 2020-12-29 14:22:29
    qt graphics view 坐标系 graphics view 有3个有效的坐标系 图形项坐标(graphics item) 场景坐标(graphics scene) 视图坐标(graphics view)

    qt graphics view 坐标系

    参考:https://blog.csdn.net/qq_40732350/article/details/90116319

    场景类:QGraphicsScene类
    视图类:QGraphicsView类
    图元类:QGraphicsItem类

    在这里插入图片描述

    1.场景坐标

    场景坐标是所有图元的基础坐标系统。场景坐标系统描述了顶层的图元,每个图元都有场景坐标和相应的包容框。场景坐标的原点在场景中心,坐标原点是x轴正方向向右,y轴正方向向下。

    QGraphicsScene类的坐标系以中心为原点(0,0),如图所示。

    graphics view 有3个有效的坐标系

    场景坐标(graphics scene)

    场景坐标是所有图元的基础坐标系统。场景坐标系统描述了顶层的图元,每个图元都有场景坐标和相应的包容框。
    场景坐标的原点在场景中心,坐标原点是x轴正方向向右,y轴正方向向下。

    QGraphicsScene类的坐标系以中心为原点(0,0),如图所示。
    在这里插入图片描述

    视图坐标(graphics view)

    视图坐标是窗口部件的坐标。视图坐标的单位是像素。

    QGraphicsView视图的左上角是(0,0),x轴正方向向右,y轴正方向向下。
    所有的鼠标事件最开始都是使用视图坐标。
    QGraphicsView类继承自QWidget类,因此它与其他的QWidget类一样,以窗口的左上角作为自己坐标系的原点,如图所示。

    在这里插入图片描述

    图元坐标

    图元使用自己的本地坐标,这个坐标系统通常以图元中心为原点,这也是所有变换的原点。图元坐标方向是x轴正方向向右,y轴正方向向下。创建图元后,只需注意图元坐标就可以了,QGraphicsScene和QGraphicsView会完成所有的变换。

    QGraphicsItem类的坐标系,若在调用QGraphicsItem类的paint()函数重绘图元时,则以此坐标系为基准,如图7.4所示。
    在这里插入图片描述
    在这里插入图片描述
    scene = new QGraphicsScene(-400, -300, 800, 600);
    在这里插入图片描述
    scene = new QGraphicsScene(-400, -300, 800, 600);

    scene 是一张画布,一张纸,
    这张纸的左上角的坐标,在scene坐标系中,定义为-400,-300,
    这张纸的长宽为800,600
    这样 就能确定 scene场景的坐标系的 原点位置。

    测试程序

    #include "tstwidget.h"
    #include "ui_tstwidget.h"
    #include <QLayout>
    #include <QDebug>
    
    
    TstWidget::TstWidget(QWidget *parent) :
        QWidget(parent),
        ui(new Ui::TstWidget)
    {
        ui->setupUi(this);
    
        _graphicsSence = new QGraphicsScene(this);
        _graphicsView = new QGraphicsView(this);
    
        _graphicsView->setAlignment(Qt::AlignCenter);
        //_graphicsView->setAlignment(Qt::AlignLeft|Qt::AlignTop);
        _graphicsView->setScene(_graphicsSence);
    
        QHBoxLayout *_topLayout = new QHBoxLayout;
        _topLayout->addWidget(_graphicsView);
        this->setLayout(_topLayout);
    
        initGraphicsView();
    
        this->resize(500,500);
    }
    
    void TstWidget::initGraphicsView()
    {
        QPen pen;
        pen.setColor(QColor(255, 0, 0));
        pen.setWidth(2);
        //_graphicsSence->setSceneRect(-100,-100,100,100);
        //_graphicsSence->addRect(-100,-100,100,100);
        qDebug()<< _graphicsSence->sceneRect() <<endl;
        //_graphicsView->setAlignment(Qt::AlignLeft | Qt::AlignTop);
        _graphicsSence->addRect(0, 0, 100, 100, pen);
    
    //    _graphicsSence->addRect(50, 50, 50, 50);
    //    _graphicsSence->addRect(0, 0, 50, 50);
    
    //    _graphicsSence->addRect(-100,-50,200,100);
        _graphicsSence->addLine(0,0,200,200);
    
    }
    
    TstWidget::~TstWidget()
    {
        delete ui;
    }
    
    

    .h头文件

    #ifndef TSTWIDGET_H
    #define TSTWIDGET_H
    
    #include <QWidget>
    #include <QGraphicsItem>
    #include <QGraphicsView>
    #include <QLayout>
    
    namespace Ui {
    class TstWidget;
    }
    
    class TstWidget : public QWidget
    {
        Q_OBJECT
    
    public:
        explicit TstWidget(QWidget *parent = nullptr);
        ~TstWidget();
    
    private:
        Ui::TstWidget *ui;
    
        QGraphicsScene* _graphicsSence;
        QGraphicsView* _graphicsView;
        QHBoxLayout *_topLayout;
        void initGraphicsView();
    };
    
    #endif // TSTWIDGET_H
    
    
    

    scene 的坐标原点与view的坐标原点之间的关系

    如果设置为
    _graphicsView->setAlignment(Qt::AlignLeft | Qt::AlignTop);
    没有下面这句话
    _graphicsSence->setSceneRect(-100,-100,100,100)

    那么scene 的坐标原点与view的坐标原点重合

    如果有那句话,
    那么view的坐标原点是 scene 的(-100,-100)

    如果设置为_graphicsView->setAlignment(Qt::AlignCenter)
    会尽量将scene中的item作为一个组合整体。
    然后找到这个组合整体的重心,放在view窗体的中心。
    scene的原点,相对偏移。

    展开全文
  • # self.graphicsView.resize(500,600) self.graphicsView.setGeometry(QtCore.QRect(40,82,500,600)) # self.graphicsView.setLayout(Layout) self.pushButton3.clicked.connect(self.graphicsView.addLine) self....
  • 本文仅供记录,各位如有参考,不胜荣幸 解决之前临时变量销毁导致的程序奔溃,使用成员变量定义 from PyQt5 import QtCore, QtGui, QtWidgets import sys from PyQt5.QtCore import * ...class GraphicsView
  • 其实在我看来这两个是异曲同工的,所以本文用GraphicsView实现对控件的提升。 一、选择控件 用GraphicsView这个,谢谢,我尝试过通过widge的显示图片地图,但是最后不能交互。(内容放在后面了,如果有大佬看到,请...
  • Pythone+pyQt5控件TreeView+ListView+GraphicsView及菜单栏使用,构建自己的图片浏览器 1、使用pyQt5的designer设计UI如下 2、编译形成.py文件,原代码如下,你可以自己编辑成文件Ui_mainwin.py备用。代码都是...
  • Graphics View Framework

    2021-03-17 11:27:56
    Graphics View Framework 文章目录Graphics View FrameworkThe Graphics View ArchitectureSceneViewItem自定义item Graphics View 提供了一个用于管理大量定制的2D 图形项目并与之交互的表层,以及一个用于可视化...
  • Qt+Graphics VIEW组件进行矢量(*.shp)图形的读取Graphics View控件介绍矢量图形读取...https://doc.qt.io/qt-5/graphicsview.html https://blog.51cto.com/9291927/1879128 矢量图形读取的准备工作 首先,由于Graph
  • 这一次将介绍如何使用Graphics View来实现前面所说的画板。前面说了不少有关Graphics View的好话,可是没有具体的实例很难说究竟好在哪里。如今咱们就把前面的内容使用Graphics View从新实现一下,你们能够对比一下...
  • 必须先放到graphicScene,然后再把graphicscene放到graphicview中 # 即 FigureCanvas -> graphicScene -> graphicview self.graphic_scene_PR.addWidget(self.graph_content_PR) # 把图形放到QGraphicsScene中,注意...
  • Graphics View Framework 类

    2021-04-08 19:46:39
    目录 QGraphicsView QGraphicsScene QGraphicsItem QAbstractGraphicsShapeItem QGraphicsEllipseItem QGraphicsPathItem QGraphicsPolygonItem QGraphicsRectItem QGraphicsSimpleTextItem QGraphicsItemGroup ...
  • 一、关于GraphicsView、GraphicsScene和GraphicsItem三个坐标系的建立 二、如何使用背景网格? 1.使用drawBackground函数 2.绘制背景网格需要避的坑 总结 目录 前言 一、关于GraphicsView、GraphicsScene和...
  • GraphicsView的坐标体系中,物体的坐标系是以物体的中心为原点(0,0),物体在几何学上的原始点通常对应物体的points,lines,rectangles。当你创建自定义物体时,QGraphicsScene和QGraphicsView会为你做好所有的坐标...
  • 一、Graphics View框架结构的主要特点 (1)在Graphics View框架结构中,系统可以利用Qt绘图系统的反锯齿、OpenGL工具来改善绘图性能。 (2) Graphics View支持事件传播体系结构,可以使图元在场景(scene) 中的交互能力...
  • 另外,为了方便,Graphics View框架也为场景以及每个item提供拖拽支持。当视图接收到拖拽事件,它可转化为QGraphicsSceneDragDropEvent,再发送到场景。场景接管这个事件,把它发送到光标下接受拖拽的第一个item。 ...
  • 1、QGraphicsScene::removeItem: item 0x1c2082795f0’s scene (0x0) is different from this scene (0x1c1bc8e2240),这个报警是由场景重复移除同一图元引起。
  • 另外,为了方便,Graphics View框架也为场景以及每个item提供拖拽支持。当视图接收到拖拽事件,它可转化为QGraphicsSceneDragDropEvent,再发送到场景。场景接管这个事件,把它发送到光标下接受拖拽的第一个item。 ...
  • 这一次将介绍如何使用Graphics View来实现前面所说的画板。前面说了很多有关Graphics View的好话,但是没有具体的实例很难说究竟好在哪里。现在我们就把前面的内容使用Graphics View重新实现一下,大家可以对比一下...
  • 这里写目录标题运行结果mainwindow.hmainwindow.cppmain.cpp 运行结果 mainwindow.h ...QGraphicsView> #include <QGraphicsScene> class MainWindow : public QMainWindow { Q_OBJECT pub
  • 本来打算使用paintEvent的,结果尝试了几个小时一直未能实现,因为paintEvent是窗口刷新就会运行,使得十字准线直接出现,而另一个问题就是无法将线条显示在graphicsView中,原因我也不太清除(如果有大佬知道请赐教...
  • Qt ⼀个简易画板的实现(Graphics View)Qt 学习之路(32): ⼀个简易画板的实现(Graphics View)这⼀次将介绍如何使⽤ Graphics View 来实现前⾯所说的画板。前⾯说了很多有关Graphics View的好话,但是 有具体的实例很...
  • 同时,QGraphicsView还提供了在视图和场景坐标之间进行转换的函数:QGraphicsView::maptosene()和QGraphicsView::mapFromScene()。 图形项   QGraphicsItem是场景中图形项的基类。典型的形状的标准图形项有矩形...
  • virtual voidhoverLeaveEvent ( QGraphicsSceneHoverEvent * event )重新编译后,可以获取到鼠标离开item范围的消息,但我需要知道按下左键并移动的范围,...代码如下:view类MyGraphView::MyGraphView(QWidget *pa...
  • Graphics View Framework Qt 学习之路 2(30):Graphics View Framework
  • 实现关键点:1)拖动:重写QGraphicsView类,鼠标中键按下记录位置并更改鼠标样式为手型,鼠标中键弹起记录鼠标位置,并执行拖动,通过设置横竖滚动条位置实现拖动;2)缩放:重写鼠标滚轮滑动事件滚轮上滑放大,...
  • 设置样式: background: transparent;border:0px
  • graphicsView->grab(); 展示代码示例: #include <QDialog> #include <QLabel> void MainWindow::on_pushButton_clicked() { QPixmap pix=ui->graphicsView->grab(); QDialog..

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 119,960
精华内容 47,984
关键字:

graphicsview

友情链接: c2.zip