crossplatform.ru

Здравствуйте, гость ( Вход | Регистрация )

_Vitaliy_
  опции профиля:
сообщение 18.9.2011, 9:09
Сообщение #1


Студент
*

Группа: Участник
Сообщений: 59
Регистрация: 20.11.2008
Пользователь №: 428

Спасибо сказали: 3 раз(а)




Репутация:   0  


Доброго времени суток.
Практически "нубский" вопрос, поэтому прошу отнестись с нисхождением, графику только осваиваю.

В связи с "корявыми руками" не получается реализовать ограничения перемещения объекта на сцене по оси "Y".

Беру пример Шлее: CustomGraphicsView, смотрю в стандартных примерах diagramscene, а именно diagramitem.h, там есть
QVariant itemChange(GraphicsItemChange change, const QVariant &value); как раз то, что нужно

но у меня не получается реализовать это в примере Шлее... выдает ошибку: 'GraphicsItemChange' has not been declared.

Взял скопировал целый класс из diagramitem.h, ошибок не выдает, но как его завязать на пример Шлее мозгов не хватает...

На всякий случай привожу код:

main.cpp
Раскрывающийся текст
/* ======================================================================
** main.cpp
** ======================================================================
**
** ======================================================================
** Copyright © 2007 by Max Schlee
** ======================================================================
*/
#include <QtGui>
#include "MyView.h"

// ======================================================================
class SimpleItem : public QGraphicsItem {
private:
enum {nPenWidth = 3};

public:
virtual QRectF boundingRect() const
{
QPointF ptPosition(-10 - nPenWidth, -10 - nPenWidth);
QSizeF size(20 + nPenWidth * 2, 20 + nPenWidth * 2);
return QRectF(ptPosition, size);
}

virtual void paint(QPainter* ppainter,
const QStyleOptionGraphicsItem*,
QWidget*
)
{
ppainter->save();
ppainter->setPen(QPen(Qt::blue, nPenWidth));
ppainter->drawEllipse(-10, -10, 20, 20);
ppainter->restore();
}

virtual void mousePressEvent(QGraphicsSceneMouseEvent* pe)
{

QApplication::setOverrideCursor(Qt::PointingHandCursor);
QGraphicsItem::mousePressEvent(pe);
}

virtual void mouseReleaseEvent(QGraphicsSceneMouseEvent* pe)
{
QApplication::restoreOverrideCursor();
QGraphicsItem::mouseReleaseEvent(pe);
}

QVariant itemChange(GraphicsItemChange change, const QVariant &value);
};

// ----------------------------------------------------------------------
int main(int argc, char** argv)
{
QApplication app(argc, argv);
QWidget wgt;
QGraphicsScene scene(QRectF(-100, -100, 640, 480));

MyView* pView = new MyView(&scene);
QPushButton* pcmdZoomIn = new QPushButton("&Zoom In");
QPushButton* pcmdZoomOut = new QPushButton("Z&oom Out");
QPushButton* pcmdRotateLeft = new QPushButton("&Rotate Left");
QPushButton* pcmdRotateRight = new QPushButton("Ro&tate Right");

pView->setRenderHint(QPainter::Antialiasing, true);

SimpleItem* pSimpleItem = new SimpleItem;
scene.addItem(pSimpleItem);
pSimpleItem->setPos(0, 0);
pSimpleItem->setFlags(QGraphicsItem::ItemIsMovable);

QGraphicsPixmapItem* pPixmapItem =
scene.addPixmap(QPixmap("haus2.jpg"));
pPixmapItem->setParentItem(pSimpleItem);
pPixmapItem->setFlags(QGraphicsItem::ItemIsMovable);

QObject::connect(pcmdZoomIn, SIGNAL(clicked()),
pView, SLOT(slotZoomIn())
);
QObject::connect(pcmdZoomOut, SIGNAL(clicked()),
pView, SLOT(slotZoomOut())
);
QObject::connect(pcmdRotateLeft, SIGNAL(clicked()),
pView, SLOT(slotRotateLeft())
);
QObject::connect(pcmdRotateRight, SIGNAL(clicked()),
pView, SLOT(slotRotateRight())
);

//Layout setup
QVBoxLayout* pvbxLayout = new QVBoxLayout;
pvbxLayout->addWidget(pView);
pvbxLayout->addWidget(pcmdZoomIn);
pvbxLayout->addWidget(pcmdZoomOut);
pvbxLayout->addWidget(pcmdRotateLeft);
pvbxLayout->addWidget(pcmdRotateRight);
wgt.setLayout(pvbxLayout);

wgt.show();

return app.exec();
}


MyView.h

Раскрывающийся текст
#ifndef _MyView_h_
#define _MyView_h_

#include <QGraphicsView>
class QGraphicsItem;
class QGraphicsScene;



#include <QList>
#include <QGraphicsPixmapItem>
#include <QList>

QT_BEGIN_NAMESPACE
class QPixmap;
class QGraphicsItem;
class QGraphicsScene;
class QTextEdit;
class QGraphicsSceneMouseEvent;
class QMenu;
class QGraphicsSceneContextMenuEvent;
class QPainter;
class QStyleOptionGraphicsItem;
class QWidget;
class QPolygonF;
QT_END_NAMESPACE

// ======================================================================
class MyView: public QGraphicsView {
Q_OBJECT
public:

MyView(QGraphicsScene* pScene, QWidget* pwgt = 0)
: QGraphicsView(pScene, pwgt)
{
}

public slots:
void slotZoomIn()
{
scale(1.1, 1.1);
}

void slotZoomOut()
{
scale(1 / 1.1, 1 / 1.1);
}

void slotRotateLeft()
{
rotate(-5);
}

void slotRotateRight()
{
rotate(5);
}

private:

};


class DiagramItem : public QGraphicsPolygonItem
{
public:
enum { Type = UserType + 15 };
enum DiagramType { Step, Conditional, StartEnd, Io };

DiagramItem(DiagramType diagramType, QMenu *contextMenu,
QGraphicsItem *parent = 0, QGraphicsScene *scene = 0);


DiagramType diagramType() const
{ return myDiagramType; }
QPolygonF polygon() const
{ return myPolygon; }

QPixmap image() const;
int type() const
{ return Type;}

protected:
void contextMenuEvent(QGraphicsSceneContextMenuEvent *event);
QVariant itemChange(GraphicsItemChange change, const QVariant &value);

private:
DiagramType myDiagramType;
QPolygonF myPolygon;
QMenu *myContextMenu;

};


Честно признаюсь, по форумам смотрел, у поисковиков спрашивал...
Просьба подсказать как реализовать или дать вектор направления.
Перейти в начало страницы
 
Быстрая цитата+Цитировать сообщение
 
Начать новую тему
Ответов (1 - 4)
_Vitaliy_
  опции профиля:
сообщение 19.9.2011, 18:57
Сообщение #2


Студент
*

Группа: Участник
Сообщений: 59
Регистрация: 20.11.2008
Пользователь №: 428

Спасибо сказали: 3 раз(а)




Репутация:   0  


Вроде получилось "прикрутить" описание + реализация, только ограничения не происходит.
Направьте на путь истинный пожалуйста!!!
(По прежнему пример из Шлее с небольшим допилом)
main.cpp
Раскрывающийся текст
/* ======================================================================
** main.cpp
** ======================================================================
**
** ======================================================================
** Copyright © 2007 by Max Schlee
** ======================================================================
*/
#include <QtGui>
#include "MyView.h"

// ======================================================================
class SimpleItem : public QGraphicsItem {
private:
enum {nPenWidth = 3};

public:

virtual QRectF boundingRect() const
{
//QPointF ptPosition(-10 - nPenWidth, -10 - nPenWidth);
//QSizeF size(20 + nPenWidth * 2, 20 + nPenWidth * 2);

QPointF ptPosition(110 - nPenWidth, 110 - nPenWidth);
QSizeF size(120 + nPenWidth * 2, 120 + nPenWidth * 2);

return QRectF(ptPosition, size);
}

virtual void paint(QPainter* ppainter,
const QStyleOptionGraphicsItem*,
QWidget*
)
{
ppainter->save();
ppainter->setPen(QPen(Qt::blue, nPenWidth));
// ppainter->drawEllipse(-10, -10, 20, 20);
ppainter->drawEllipse(100, 100, 110, 110);
ppainter->restore();
}

virtual void mousePressEvent(QGraphicsSceneMouseEvent* pe)
{

QApplication::setOverrideCursor(Qt::PointingHandCursor);
QGraphicsItem::mousePressEvent(pe);
}

virtual void mouseReleaseEvent(QGraphicsSceneMouseEvent* pe)
{
QApplication::restoreOverrideCursor();
QGraphicsItem::mouseReleaseEvent(pe);
}

protected:

QVariant itemChange(GraphicsItemChange change,
const QVariant &value);


};

QVariant SimpleItem::itemChange(GraphicsItemChange change, const QVariant &value)
{
if (change == ItemPositionChange && scene()) {
// value is the new position.
QPointF newPos = value.toPointF();
newPos.setX(x()); // ogranichenie po osi X
QRectF rect = scene()->sceneRect();
if (!rect.contains(newPos)) {
// Keep the item inside the scene rect.
newPos.setX(qMin(rect.right(), qMax(newPos.x(), rect.left())));
newPos.setY(qMin(rect.bottom(), qMax(newPos.y(), rect.top())));
return newPos;
}
}
return QGraphicsItem::itemChange(change, value);
}

// ----------------------------------------------------------------------
int main(int argc, char** argv)
{
QApplication app(argc, argv);
QWidget wgt;
//QGraphicsScene scene(QRectF(-100, -100, 640, 480));
QGraphicsScene scene(QRectF(10, 10, 640, 480));
MyView* pView = new MyView(&scene);
QPushButton* pcmdZoomIn = new QPushButton("&Zoom In");
QPushButton* pcmdZoomOut = new QPushButton("Z&oom Out");
QPushButton* pcmdRotateLeft = new QPushButton("&Rotate Left");
QPushButton* pcmdRotateRight = new QPushButton("Ro&tate Right");


scene.setBackgroundBrush(Qt::lightGray);


pView->setRenderHint(QPainter::Antialiasing, true);

SimpleItem* pSimpleItem = new SimpleItem;
scene.addItem(pSimpleItem);
pSimpleItem->setPos(0, 0);
pSimpleItem->setFlags(QGraphicsItem::ItemIsMovable);

QGraphicsLineItem* pLineItem =
scene.addLine(QLineF(20, 20, 80, 80), QPen(Qt::red, 2));
//scene.addLine(QLineF(-30, -30, 30, 30), QPen(Qt::green, 3));
pLineItem->setParentItem(pSimpleItem);
pLineItem->setFlags(QGraphicsItem::ItemIsMovable);

pLineItem->setFlags(QGraphicsItem::ItemIsMovable);
pLineItem->setPos(0, 130); // otobrazit v nuzhnom meste


QObject::connect(pcmdZoomIn, SIGNAL(clicked()),
pView, SLOT(slotZoomIn())
);
QObject::connect(pcmdZoomOut, SIGNAL(clicked()),
pView, SLOT(slotZoomOut())
);
QObject::connect(pcmdRotateLeft, SIGNAL(clicked()),
pView, SLOT(slotRotateLeft())
);
QObject::connect(pcmdRotateRight, SIGNAL(clicked()),
pView, SLOT(slotRotateRight())
);

//Layout setup
QVBoxLayout* pvbxLayout = new QVBoxLayout;
pvbxLayout->addWidget(pView);
pvbxLayout->addWidget(pcmdZoomIn);
pvbxLayout->addWidget(pcmdZoomOut);
pvbxLayout->addWidget(pcmdRotateLeft);
pvbxLayout->addWidget(pcmdRotateRight);
wgt.setLayout(pvbxLayout);

wgt.show();

return app.exec();
}


MyView.h
Раскрывающийся текст
/* ======================================================================
** MyView.h
** ======================================================================
**
** ======================================================================
** Copyright © 2007 by Max Schlee
** ======================================================================
*/

#ifndef _MyView_h_
#define _MyView_h_

#include <QGraphicsView>
#include <QGraphicsItem>
#include <QVariant>

#include <QApplication>
#include <QColor>
#include <QGraphicsItem>
#include <QSet>

// ======================================================================
class MyView: public QGraphicsView {
Q_OBJECT
public:
MyView(QGraphicsScene* pScene, QWidget* pwgt = 0)
: QGraphicsView(pScene, pwgt)

{
}

public slots:
void slotZoomIn()
{
scale(1.1, 1.1);
}

void slotZoomOut()
{
scale(1 / 1.1, 1 / 1.1);
}

void slotRotateLeft()
{
rotate(-5);
}

void slotRotateRight()
{
rotate(5);
}

};

#endif //_MyView_h_
Перейти в начало страницы
 
Быстрая цитата+Цитировать сообщение
ssoft
  опции профиля:
сообщение 20.9.2011, 11:01
Сообщение #3


Участник
**

Группа: Участник
Сообщений: 130
Регистрация: 17.2.2010
Из: Москва
Пользователь №: 1470

Спасибо сказали: 30 раз(а)




Репутация:   3  


Чтобы ограничить перемещения Item, нужно отключить флаг ItemIsMovable, и самому управлять координатами Item через обработку события mouseMoveEvent.
При обработке события можно изменять (ограничивать) перемещения объекта как заблагорассудится.
Перейти в начало страницы
 
Быстрая цитата+Цитировать сообщение
_Vitaliy_
  опции профиля:
сообщение 22.9.2011, 18:32
Сообщение #4


Студент
*

Группа: Участник
Сообщений: 59
Регистрация: 20.11.2008
Пользователь №: 428

Спасибо сказали: 3 раз(а)




Репутация:   0  


Цитата(ssoft @ 20.9.2011, 11:01) Link
Чтобы ограничить перемещения Item, нужно отключить флаг ItemIsMovable, и самому управлять координатами Item через обработку события mouseMoveEvent.
При обработке события можно изменять (ограничивать) перемещения объекта как заблагорассудится.


Попробовал, как Вы сказали ssoft, однако перемещения вообще НЕТ, привожу код другого упрощенного примера (только main.cpp):
#include <QtGui>

class SimpleItem : public QGraphicsItem {

public:
    SimpleItem(QGraphicsItem *parent = 0)
        : QGraphicsItem(parent)
{}

QRectF boundingRect() const
{
    return QRectF(0,0,100,100);
}

void paint(QPainter *painter,
               const QStyleOptionGraphicsItem *option,
               QWidget *viewport)
    {
    painter->setPen(QPen(Qt::red, 3));
    painter->drawEllipse(0,0,100,100);

    }

protected:
    void mousePressEvent(QGraphicsSceneMouseEvent * event)
    {
        if (event->pos().x() > 0)
            event->ignore();

        qDebug() << "Press at local pos" << event->pos();
        qDebug() << "Press at scene pos" << event->scenePos();
        qDebug() << "Press at screen pos" << event->screenPos();
    }

    void mouseMoveEvent(QGraphicsSceneMouseEvent *event)
    {
        qDebug() << "Move at local pos" << event->pos();
        qDebug() << "  distance from last pos:"
                 << QLineF(event->lastPos(), event->pos()).length();
    }

};

int main(int argc, char **argv)
{
    QApplication app(argc, argv);
    QGraphicsScene scene(QRectF(5, 5, 160, 160));

    QGraphicsLineItem* pLineItem =
    scene.addLine(QLineF(20, 20, 80, 80), QPen(Qt::blue, 2));
    pLineItem->setFlags(QGraphicsItem::ItemIsMovable);

    QGraphicsItem *sm = new SimpleItem();
    sm->setFlags(QGraphicsItem::ItemIsMovable);
    scene.addItem(sm);

    QGraphicsView view(&scene);
     //     view.setDragMode(QGraphicsView::ScrollHandDrag);
     //   view.setDragMode(QGraphicsView::RubberBandDrag);
    view.show();
    return app.exec();
}

прошу помощи, уже устал с этим бороться...
Перейти в начало страницы
 
Быстрая цитата+Цитировать сообщение
_Vitaliy_
  опции профиля:
сообщение 23.9.2011, 12:23
Сообщение #5


Студент
*

Группа: Участник
Сообщений: 59
Регистрация: 20.11.2008
Пользователь №: 428

Спасибо сказали: 3 раз(а)




Репутация:   0  


Решил вопрос. Надо было работать с сценой а не непрямую. Тему можно закрывать.
Перейти в начало страницы
 
Быстрая цитата+Цитировать сообщение

Быстрый ответОтветить в данную темуНачать новую тему
Теги
Нет тегов для показа


1 чел. читают эту тему (гостей: 1, скрытых пользователей: 0)
Пользователей: 0


RSS Рейтинг@Mail.ru Текстовая версия Сейчас: 7.8.2025, 14:56