QSlider mouse direct jump - qt

Instead of stepping when the user clicks somewhere on the qslider I want to make the slider jump to that position. How can this be implemented ?

after having problems with all versions of #spyke #Massimo Callegari and #Ben (slider position wasnt correct for the whole area) I found some Qt Style functionality within QSlider sourcecode: QStyle::SH_Slider_AbsoluteSetButtons.
You have to create a new QStyle which can be a very annoying, or you use ProxyStyle as shown by user jpn in http://www.qtcentre.org/threads/9208-QSlider-step-customize?p=49035#post49035
I've added another constructor and fixed a typo, but used the rest of the original source code.
#include <QProxyStyle>
class MyStyle : public QProxyStyle
{
public:
using QProxyStyle::QProxyStyle;
int styleHint(QStyle::StyleHint hint, const QStyleOption* option = 0, const QWidget* widget = 0, QStyleHintReturn* returnData = 0) const
{
if (hint == QStyle::SH_Slider_AbsoluteSetButtons)
return (Qt::LeftButton | Qt::MidButton | Qt::RightButton);
return QProxyStyle::styleHint(hint, option, widget, returnData);
}
};
now you can set the style of your slider in the sliders constructor (if your slider is derived from QSlider):
setStyle(new MyStyle(this->style()));
or it should work this way if it is a standard QSlider:
standardSlider.setStyle(new MyStyle(standardSlider->style()));
so you use the original style of that element, but if the QStyle::SH_Slider_AbsoluteSetButtons "property" is asked you return as you want ;)
maybe you'll have to destroy these proxystyles on slider deletion, not tested yet.

Well, I doubt that Qt has a direct function for this purpose.
Try to use custom widgets. This should work!
Try the following logic
class MySlider : public QSlider
{
protected:
void mousePressEvent ( QMouseEvent * event )
{
if (event->button() == Qt::LeftButton)
{
if (orientation() == Qt::Vertical)
setValue(minimum() + ((maximum()-minimum()) * (height()-event->y())) / height() ) ;
else
setValue(minimum() + ((maximum()-minimum()) * event->x()) / width() ) ;
event->accept();
}
QSlider::mousePressEvent(event);
}
};

I needed this too and tried spyke solution, but it's missing two things:
inverted appearance
handle picking (when the mouse is over the handle, direct jump is not necessary)
So, here's the reviewed code:
void MySlider::mousePressEvent ( QMouseEvent * event )
{
QStyleOptionSlider opt;
initStyleOption(&opt);
QRect sr = style()->subControlRect(QStyle::CC_Slider, &opt, QStyle::SC_SliderHandle, this);
if (event->button() == Qt::LeftButton &&
sr.contains(event->pos()) == false)
{
int newVal;
if (orientation() == Qt::Vertical)
newVal = minimum() + ((maximum()-minimum()) * (height()-event->y())) / height();
else
newVal = minimum() + ((maximum()-minimum()) * event->x()) / width();
if (invertedAppearance() == true)
setValue( maximum() - newVal );
else
setValue(newVal);
event->accept();
}
QSlider::mousePressEvent(event);
}

The answer of Massimo Callegari is almost right, but the calculation of newVal ignores the slider handle width. This problem comes up when you try to click near the end of the slider.
The following code fixes this for horizontal sliders
double halfHandleWidth = (0.5 * sr.width()) + 0.5; // Correct rounding
int adaptedPosX = event->x();
if ( adaptedPosX < halfHandleWidth )
adaptedPosX = halfHandleWidth;
if ( adaptedPosX > width() - halfHandleWidth )
adaptedPosX = width() - halfHandleWidth;
// get new dimensions accounting for slider handle width
double newWidth = (width() - halfHandleWidth) - halfHandleWidth;
double normalizedPosition = (adaptedPosX - halfHandleWidth) / newWidth ;
newVal = minimum() + ((maximum()-minimum()) * normalizedPosition);

Here is a simple implementation in python using QStyle.sliderValueFromPosition():
class JumpSlider(QtGui.QSlider):
def mousePressEvent(self, ev):
""" Jump to click position """
self.setValue(QtGui.QStyle.sliderValueFromPosition(self.minimum(), self.maximum(), ev.x(), self.width()))
def mouseMoveEvent(self, ev):
""" Jump to pointer position while moving """
self.setValue(QtGui.QStyle.sliderValueFromPosition(self.minimum(), self.maximum(), ev.x(), self.width()))

The following code is actually a hack, but it works fine without sub-classing QSlider. The only thing you need to do is to connect QSlider valueChanged signal to your container.
Note1: You must set a pageStep > 0 in your slider
Note2: It works only for an horizontal, left-to-right slider (you should change the calculation of "sliderPosUnderMouse" to work with vertical orientation or inverted appearance)
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
// ...
connect(ui->mySlider, SIGNAL(valueChanged(int)),
this, SLOT(mySliderValueChanged(int)));
// ...
}
void MainWindow::mySliderValueChanged(int newPos)
{
// Make slider to follow the mouse directly and not by pageStep steps
Qt::MouseButtons btns = QApplication::mouseButtons();
QPoint localMousePos = ui->mySlider->mapFromGlobal(QCursor::pos());
bool clickOnSlider = (btns & Qt::LeftButton) &&
(localMousePos.x() >= 0 && localMousePos.y() >= 0 &&
localMousePos.x() < ui->mySlider->size().width() &&
localMousePos.y() < ui->mySlider->size().height());
if (clickOnSlider)
{
// Attention! The following works only for Horizontal, Left-to-right sliders
float posRatio = localMousePos.x() / (float )ui->mySlider->size().width();
int sliderRange = ui->mySlider->maximum() - ui->mySlider->minimum();
int sliderPosUnderMouse = ui->mySlider->minimum() + sliderRange * posRatio;
if (sliderPosUnderMouse != newPos)
{
ui->mySlider->setValue(sliderPosUnderMouse);
return;
}
}
// ...
}

My final implementation based on surrounding comments:
class ClickableSlider : public QSlider {
public:
ClickableSlider(QWidget *parent = 0) : QSlider(parent) {}
protected:
void ClickableSlider::mousePressEvent(QMouseEvent *event) {
QStyleOptionSlider opt;
initStyleOption(&opt);
QRect sr = style()->subControlRect(QStyle::CC_Slider, &opt, QStyle::SC_SliderHandle, this);
if (event->button() == Qt::LeftButton &&
!sr.contains(event->pos())) {
int newVal;
if (orientation() == Qt::Vertical) {
double halfHandleHeight = (0.5 * sr.height()) + 0.5;
int adaptedPosY = height() - event->y();
if ( adaptedPosY < halfHandleHeight )
adaptedPosY = halfHandleHeight;
if ( adaptedPosY > height() - halfHandleHeight )
adaptedPosY = height() - halfHandleHeight;
double newHeight = (height() - halfHandleHeight) - halfHandleHeight;
double normalizedPosition = (adaptedPosY - halfHandleHeight) / newHeight ;
newVal = minimum() + (maximum()-minimum()) * normalizedPosition;
} else {
double halfHandleWidth = (0.5 * sr.width()) + 0.5;
int adaptedPosX = event->x();
if ( adaptedPosX < halfHandleWidth )
adaptedPosX = halfHandleWidth;
if ( adaptedPosX > width() - halfHandleWidth )
adaptedPosX = width() - halfHandleWidth;
double newWidth = (width() - halfHandleWidth) - halfHandleWidth;
double normalizedPosition = (adaptedPosX - halfHandleWidth) / newWidth ;
newVal = minimum() + ((maximum()-minimum()) * normalizedPosition);
}
if (invertedAppearance())
setValue( maximum() - newVal );
else
setValue(newVal);
event->accept();
} else {
QSlider::mousePressEvent(event);
}
}
};

This modification to the JumpSlider above works in PyQt5:
class JumpSlider(QSlider):
def _FixPositionToInterval(self,ev):
""" Function to force the slider position to be on tick locations """
# Get the value from the slider
Value=QStyle.sliderValueFromPosition(self.minimum(), self.maximum(), ev.x(), self.width())
# Get the desired tick interval from the slider
TickInterval=self.tickInterval()
# Convert the value to be only at the tick interval locations
Value=round(Value/TickInterval)*TickInterval
# Set the position of the slider based on the interval position
self.setValue(Value)
def mousePressEvent(self, ev):
self._FixPositionToInterval(ev)
def mouseMoveEvent(self, ev):
self._FixPositionToInterval(ev)

I think,
the QStyle::sliderValueFromPosition() function can be used.
http://qt-project.org/doc/qt-5/qstyle.html#sliderValueFromPosition

i have been trying and searching this on net and was expecting Qt for a smarter way doing this, unfortunately there was not big help (may be i was not searching properly )
well i have done this in Qt creator:
Add an eventFilter in header ( takes QObject and QEvent as argument ) (bool return type)
Initialize in constructor ..for eg .. if ur slider is HSlider then
ui->HSlider->installEventFilter(this);
In the defination :
a. check if the object is your slider type something like : ui->HSlider == Object
b. Check for mouse click event something like : QEvent::MouseButtonPress == event->type
c. if the above all passes means u have got mouse event on the slider do something like : in definition : ui->HSlider->setValue( Qcursor::pos().x() - firstval ); return QMainWindow::eventFilter(object, event);
Note: fistVal : can be taken out by printing the cursur position at 0 = initial position of the slider ( with help of QCursor::pos().x() )
hope this helps

A simple method would be to derive from QSlider and reimplement mousePressEvent(....) to set the marker position using setSliderPosition(int).

I also met this problem. My solution is shown below.
slider->installEventFilter(this);
---
bool MyDialog::eventFilter(QObject *object, QEvent *event)
{
if (object == slider && slider->isEnabled())
{
if (event->type() == QEvent::MouseButtonPress)
{
auto mevent = static_cast<QMouseEvent *>(event);
qreal value = slider->minimum() + (slider->maximum() - slider->minimum()) * mevent->localPos().x() / slider->width();
if (mevent->button() == Qt::LeftButton)
{
slider->setValue(qRound(value));
}
event->accept();
return true;
}
if (event->type() == QEvent::MouseMove)
{
auto mevent = static_cast<QMouseEvent *>(event);
qreal value = slider->minimum() + (slider->maximum() - slider->minimum()) * mevent->localPos().x() / slider->width();
if (mevent->buttons() & Qt::LeftButton)
{
slider->setValue(qRound(value));
}
event->accept();
return true;
}
if (event->type() == QEvent::MouseButtonDblClick)
{
event->accept();
return true;
}
}
return QDialog::eventFilter(object, event);
}
You can also override these event handlers of QSlider.
QSlider::mousePressedEvent
QSlider::mouseMoveEvent
QSlider::mouseDoubleClickEvent

Related

How to not trigger the hover state when mouse is at the corner of a round QPushButton?

I have a QPushButton with round corners:
Now, I want to changed the button's style when mouse is moving at it:
I used setStyleSheet of QPushButton:
QPushButton{
width:100px;
height:80px;
border-radius:40px;
border: 1px solid #ffffff;
}
QPushButton:hover{
background: red;
}
But not four corners:
as the 3rd image shown, the cursor is pointing at the button's right-bottom corner but aslo triggered the button's hover state. Is there a simple way to prevent this behavior?
Maybe, there exists a more straightforward solution of that, but I just tried and it occured that implementing all the hover behaviour by hand seems the only really working way.
Generally, it's all about checking that the mouse coordinates belong to an ellipse (you can try other geometric considerations).
Something that doesn't work:
ui->myButton->installEventFilter(this);
//----------------------------------------
bool SomeWidget::eventFilter(QObject *obj, QEvent *event)
{
if (event->type() == QEvent::HoverEnter || event->type() == QEvent::HoverMove)
{
QHoverEvent* hoverEvent = static_cast<QHoverEvent *>(event);
QWidget* target = qobject_cast<QWidget *>(obj);
qreal a = target->width() / 2;
qreal b = target->height() / 2;
qreal x = hoverEvent->posF().x() - a;
qreal y = hoverEvent->posF().y() - b;
double val = (x / a) * (x / a) + (y / b) * (y / b);
bool isInside = val <= 1;
if (!isInside)
return true;
else
return QObject::eventFilter(obj, event);
}
return QObject::eventFilter(obj, event);
}
With SomeWidget, comtaining a button and event filter installed, this looked promising but works awfully =(
Something that works as a Proof-of-Concept:
CustomButton::CustomButton(QWidget *parent)
: QPushButton(parent)
{
setProperty("my_hover", "not_hovered");
}
void CustomButton::mouseMoveEvent(QMouseEvent *event)
{
qreal a = width() / 2;
qreal b = height() / 2;
qreal x = event->pos().x() - a;
qreal y = event->pos().y() - b;
double val = (x / a) * (x / a) + (y / b) * (y / b);
bool isInside = val <= 1;
setProperty("my_hover", isInside ? "hovered" : "not_hovered" );
style()->unpolish(this);
style()->polish(this);
}
Subclassing a QPushButton worked better (code above is made a readble sample, you can improve it, of course). When implemented, it provides the button class with a custom property, which could be used like that:
QPushButton[my_hover="hovered"]
{
background: red;
}
To make it a perfect solution you'll probably have to care about mouseLeaveEvent too, thus getting rid of occasional glitches. Also, the property could probably be made boolean if it works with your Qt.
AFAIK, that's the only sure way to implement the desired behaviour you've descrived.

QTableView: interactive column resize without QHeaderView

I have a QTableView with a hidden horizontal header
table->horizontalHeader()->hide();
As you can see, the text in the central column is clipped because of the column width.
To view the text, the user would need to resize the column, but without a header, I am unable to do this.
What I would like to be able to do is hover my mouse over the edge of the column and have the normal resize icon appear, and then allow the user to drag the column wider.
Is this possible?
Got something to work using event filters and the following two classes...
/*
* Subclass of QTableView that provides notification when the mouse cursor
* enters/leaves a column boundary.
*/
class headerless_table_view: public QTableView {
using super = QTableView;
public:
explicit headerless_table_view (QWidget *parent = nullptr)
: super(parent)
, m_boundary_width(10)
, m_column_index(-1)
{
viewport()->setMouseTracking(true);
viewport()->installEventFilter(this);
}
/*
* #return The index of the column whose right hand boundary the cursor lies
* on or -1 if not on a boundary.
*/
int column_index () const
{
return(m_column_index);
}
protected:
virtual bool eventFilter (QObject *obj, QEvent *event) override
{
if (event->type() == QEvent::MouseMove) {
if (auto *e = dynamic_cast<QMouseEvent *>(event)) {
auto col_left = columnAt(e->pos().x() - m_boundary_width / 2);
auto col_right = columnAt(e->pos().x() + m_boundary_width / 2);
bool was_on_boundary = m_column_index != -1;
if (col_left != col_right) {
if (m_column_index == -1) {
if (col_left != -1) {
m_column_index = col_left;
}
}
} else {
m_column_index = -1;
}
bool is_on_boundary = m_column_index != -1;
if (is_on_boundary != was_on_boundary) {
entered_column_boundary(is_on_boundary);
}
}
}
return(super::eventFilter(obj, event));
}
/*
* Called whenever the cursor enters or leaves a column boundary. if
* `entered' is true then the index of the column can be obtained using
* `column_index()'.
*/
virtual void entered_column_boundary (bool entered)
{
}
private:
int m_boundary_width;
int m_column_index;
};
/*
* Subclass of headerless_table_view that allows resizing of columns.
*/
class resizable_headerless_table_view: public headerless_table_view {
using super = headerless_table_view;
public:
explicit resizable_headerless_table_view (QWidget *parent = nullptr)
: super(parent)
, m_dragging(false)
{
viewport()->installEventFilter(this);
}
protected:
virtual bool eventFilter (QObject *obj, QEvent *event) override
{
if (auto *e = dynamic_cast<QMouseEvent *>(event)) {
if (event->type() == QEvent::MouseButtonPress) {
if (column_index() != -1) {
m_mouse_pos = e->pos();
m_dragging = true;
return(true);
}
} else if (event->type() == QEvent::MouseButtonRelease) {
m_dragging = false;
} else if (event->type() == QEvent::MouseMove) {
if (m_dragging) {
int delta = e->pos().x() - m_mouse_pos.x();
setColumnWidth(column_index(), columnWidth(column_index()) + delta);
m_mouse_pos = e->pos();
return(true);
}
}
}
return(super::eventFilter(obj, event));
}
/*
* Override entered_column_boundary to update the cursor sprite when
* entering/leaving a column boundary.
*/
virtual void entered_column_boundary (bool entered) override
{
if (entered) {
m_cursor = viewport()->cursor();
viewport()->setCursor(QCursor(Qt::SplitHCursor));
} else {
viewport()->setCursor(m_cursor);
}
}
private:
bool m_dragging;
QPoint m_mouse_pos;
QCursor m_cursor;
};
I ended up splitting it across two classes as it seemed cleaner.
Anyway, simply replacing QTableView with resizable_headerless_table_view in some old example code I found seemed to have the desired effect -- the cursor sprite changes when the mouse is over a column boundary and the relevant boundary can be dragged.
Not sure how close it is to what you're after, but...

How can i change order of widget in layout by drag and drop with the mouse?

I make my own class from QWidget with redefine of paintEvent(), mousePressEvent(), mouseReleaseEvent() and mouseMoveEvent(). All that methods for move widgets over other widget (yellow).
When i create my widgets in a layout, it looks like this:
But when I move black widget to the bottom and red to the top like this:
and resize window, all widgets refresh to their align positions:
But i want, when i move one widget higher then another, the widgets should align in layout in new places, like this:
Which function i should redefine to do it?
P.S.
There is a piece of code, that can move widgets positions inside layout (change their indexes), but i don't know how find out their (x,y) position to calculate new indexes in layout. I think, that i can do it in resizeEvent().
But it when it event was emitted, positions already changed to old. (like before moveing on 1 picture), and i need positions after moveing (like on secon picture). How can i get position of widget before it will be aligned?
or How can i change order of widget in layout by drag and drop with the mouse?
I write my own widget, then redefine following methods: mouseReleaseEvent(), paintEvent(), mousePressEvent(), mouseMoveEvent(). In mousePressEvent() I hold old X and Y positions and mouse position on figure. Then in mouseMoveEvent() i calculate if minimum distance of mouse move is riched and move widget to new position (it not moves widget index in layout). After it, if emitted mouseReleaseEvent() i just calculate new index of moving widget and change and update parent layout. If widget moves less then it height, then layout just updates without changing widget index.
void SimpleWidget::mouseMoveEvent(QMouseEvent *event)
{
if (!(event->buttons() & Qt::LeftButton))
return;
if (!IsMinimumDistanceRiched(event))
{
return;
}
int y = event->globalY() - mouseClickY + oldY;
int BottomBorder = parentWidget->geometry().height() - this->geometry().height();
if(y < 0) y = 0;
else if(y > BottomBorder) y = BottomBorder;
move(oldX, y);
}
void SimpleWidget::mousePressEvent(QMouseEvent *event)
{
if (event->buttons() & Qt::LeftButton)
dragStartPosition = event->pos();
oldX = this->geometry().x();
oldY = this->geometry().y();
mouseClickX = event->globalX();
mouseClickY = event->globalY();
}
bool SimpleWidget::IsMinimumDistanceRiched(QMouseEvent *event)
{
return (event->pos() - dragStartPosition).manhattanLength() >= QApplication::startDragDistance();
}
bool SimpleWidget::moveInLayout(QWidget *widget, MoveDirection direction)
{
QVBoxLayout* myLayout = qobject_cast<QVBoxLayout*>(widget->parentWidget()->layout());
const int index = myLayout->indexOf(widget);
if (direction == MoveUp && index == 0)
{
return false;
}
if (direction == MoveDown && index == myLayout->count()-1 )
{
return false;
}
const int newIndex = direction == MoveUp ? index - 1 : index + 1;
myLayout->removeWidget(widget);
myLayout->insertWidget(newIndex , widget);
return true;
}
void SimpleWidget::paintEvent(QPaintEvent *)
{
QStyleOption o;
o.initFrom(this);
QPainter p(this);
style()->drawPrimitive(QStyle::PE_Widget, &o, &p, this);
}
void SimpleWidget::mouseReleaseEvent(QMouseEvent *)
{
int y = geometry().y();
MoveDirection direct;
int offset;
if(oldY > y)
{
offset = oldY - y;
direct = MoveUp;
}
else if(oldY < y)
{
offset = y - oldY;
direct = MoveDown;
}
int count = offset/height();
for(int i = 0; i < count; i++)
{
moveInLayout(this, direct);
}
update();
QVBoxLayout* myLayout = qobject_cast<QVBoxLayout*>(this->parentWidget->layout());
myLayout->update();
this->saveGeometry();
}

Qt 5 : Mouse Wheel event behaviour for zooming image

I have a window, in which is a QGraphicsView, which will be displaying an image. I have implemented the wheelEvent(). My images are mostly going to be bigger than the window, so I get scroll bars in the window.
What we normally observe when we rotate the wheel while viewing an image in Windows Photo Viewer is that when we move the wheel up (towards it's wire), the image zooms in and when we move it down (towards out body), the image zooms out.
What I am getting instead is when I move the wheel towards myself (to zoom out) the image instead of zooming out , first scrolls down, and starts zooming out only when the scroll bar touches its bottom most point.
It would be better to understand the problem by trying out the code. I am not able to explain in I guess.
I want the standard behavior. What to do?
Code
#include "viewer.h"
#include "ui_viewer.h"
#include <QGraphicsView>
#include <QGraphicsItem>
#include <QGraphicsPixmapItem>
#include <QWheelEvent>
#include <QDebug>
#include <QImage>
#include <QImageReader>
#include <QApplication>
#include <QDesktopWidget>
viewer::viewer(QWidget *parent) : QWidget(parent),ui2(new Ui::viewer)
{
ui2->setupUi(this);
}
viewer::~viewer()
{
delete ui2;
}
int viewer::show_changes(QString folder)
{
QDesktopWidget *desktop = QApplication::desktop();
int screenWidth = desktop->width();
int screenHeight = desktop->height();
QString filename = "image_bigger_than_window.jpg";
QPixmap pixmap = QPixmap(filename);
QImageReader reader(filename);
QImage image = reader.read();
QSize size = image.size();
int width = 800;
int height = (width * size.height()) / size.width();
int x = (screenWidth - width) / 2;
int y = (screenHeight - height) / 2 - 30;
setGeometry(x,y,width, height);
setWindowTitle("OUTPUT");
ui2->graphicsView->setGeometry(0,0,width,height);
QGraphicsScene* viewScene = new QGraphicsScene(QRectF(0, 0,width, height), 0);
QGraphicsPixmapItem *item = viewScene->addPixmap(pixmap.scaled(QSize((int)viewScene->width(), (int)viewScene->height()),
Qt::IgnoreAspectRatio, Qt::SmoothTransformation));
viewScene->addItem(item);
ui2->graphicsView->fitInView(QRectF(0, 0, width, height),Qt::IgnoreAspectRatio);
ui2->graphicsView->setScene(viewScene);
ui2->graphicsView->show();
return 0;
}
void viewer::wheelEvent(QWheelEvent * event)
{
const int degrees = event->delta() / 8;
qDebug() << degrees;
int steps = degrees / 15;
double scaleFactor = 1.0;
const qreal minFactor = 1.0;
const qreal maxFactor = 10.0;
qreal h11 = 1.0, h22 = 0;
if(steps > 0)
{
h11 = (h11 >= maxFactor) ? h11 : (h11 + scaleFactor);
h22 = (h22 >= maxFactor) ? h22 : (h22 + scaleFactor);
}
else
{
h11 = (h11 <= minFactor) ? minFactor : (h11 - scaleFactor);
h22 = (h22 <= minFactor) ? minFactor : (h22 - scaleFactor);
}
ui2->graphicsView->setTransformationAnchor(QGraphicsView::AnchorUnderMouse);
ui2->graphicsView->setTransform(QTransform(h11, 0, 0,0, h22, 0, 0,0,1));
}
EDIT
1)Removed function void viewer::wheelEvent(QWheelEvent * event) from viewer.cpp
2)Put bool viewer::eventFilter(QObject *obj, QEvent *event) in its place as a protected function and void viewer::handleWheelOnGraphicsScene(QGraphicsSceneWheelEvent* scrollevent) as a public slot in viewer.h
bool viewer::eventFilter(QObject *obj, QEvent *event)
{
if (event->type() == QEvent::GraphicsSceneWheel)
{
QGraphicsSceneWheelEvent *scrollevent = static_cast<QGraphicsSceneWheelEvent *>(event);
handleWheelOnGraphicsScene(scrollevent);
return true;
}
// Other events should propagate - what do you mean by propagate here?
return false;
}
void viewer::handleWheelOnGraphicsScene(QGraphicsSceneWheelEvent* scrollevent)
{
const int degrees = scrollevent->delta() / 8;
qDebug() << degrees;
int steps = degrees / 15;
qDebug() << steps;
double scaleFactor = 1.0; //How fast we zoom
const qreal minFactor = 1.0;
const qreal maxFactor = 10.0;
if(steps > 0)
{
h11 = (h11 >= maxFactor) ? h11 : (h11 + scaleFactor);
h22 = (h22 >= maxFactor) ? h22 : (h22 + scaleFactor);
}
else
{
h11 = (h11 <= minFactor) ? minFactor : (h11 - scaleFactor);
h22 = (h22 <= minFactor) ? minFactor : (h22 - scaleFactor);
}
ui2->graphicsView->setTransformationAnchor(QGraphicsView::AnchorUnderMouse);
ui2->graphicsView->setTransform(QTransform(h11, 0, 0,0, h22, 0, 0,0,1));
}
The code shows that you didn't subclass QGraphicsView, but instead use one in your own widget.
The wheel event will be first sent to the actual graphics view widget. There it is handled with Qt's default behaviour, namely scrolling. Only if you scrolled to the bottom, the graphics view cannot handle the wheel event, and it is propagated to its parent, your class. That's why you only can zoom when scrolled to the border.
To fix this, you should install an event filter. That allows you to intercept the wheel event and process it in your class:
// Outline, not tested
viewer::viewer(QWidget *parent) : QWidget(parent),ui2(new Ui::viewer)
{
ui2->setupUi(this);
// Let me handle your events
ui2->graphicsView->installEventFilter(this);
}
// should be protected
bool viewer::eventFilter(QObject *obj, QEvent *event) {
if (event->type() == QEvent::GraphicsSceneWheel) {
// Your implementation.
// You can't use QWheelEvent, as Graphicscene works with its own events...
handleWheelOnGraphicsScene(static_cast<QGraphicsSceneWheelEvent*> (event));
// Don't propagate
return true;
}
// Other events should propagate
return false;
}
Update
I just figured out that the event filter will not recieve GraphicsSceneWheel events on the graphics view. Instead, you have to install the filter on the Graphics Scene. Also, you have to call event->accept() so that it will not propagated.
So Updated Code:
// In Constructor, or where appropriate
ui2->graphicsView->scene()->installEventFilter(this);
bool viewer::eventFilter(QObject *obj, QEvent *event) {
if (event->type() == QEvent::GraphicsSceneWheel) {
handleWheelOnGraphicsScene(static_cast<QGraphicsSceneWheelEvent*> (event));
// Don't propagate
event->accept();
return true;
}
return false;
}
also note that handleWheelOnGraphicsScene or whatever you want to call it, should be a private method, and doesn't have to be a slot.

Qt: algorithm to rotate and resize a qgraphicslineitem present on a qgraphicsscene

Can someone please share the algorithm to rotate and resize a QGraphicsLineItem present on a QGraphicsScene? I wish to be able to click on either end of the line and rotate it while the opposite end automatically becomes the anchor point for rotation.
I have tried the solution given below and it works brilliantly!!. The solution is for line rotation only. This solution is provided to me when i posted the question at other Qt platform. All the credit goes to original author who provided the solution to me.
void Line::mousePressEvent( QGraphicsSceneMouseEvent * event ){
const QPointF pos = event->pos();
const qreal l1 = QLineF( pos, this->line().p1() ).length();
const qreal l2 = QLineF( pos, this->line().p2() ).length();
const qreal threshold = 3.5;
if( l1 < l2 and l1 < threshold ){
_dragIndex = 1;
} else if ( l2 < l1 and l2 < threshold ){
_dragIndex = 0;
} else{
_dragIndex = -1;
}
event->setAccepted( _dragIndex != -1 );
}
void Line::mouseMoveEvent( QGraphicsSceneMouseEvent * event ){
if( _dragIndex != -1 ){
const QPointF anchor = _dragIndex == 0 ? this->line().p1() : this->line().p2();
QLineF ma = QLineF(anchor,event->pos());
ma.setLength( line().length() );
const QPointF rotated = anchor + QPointF( ma.dx(), ma.dy() );
this->setLine( _dragIndex == 0 ? QLineF(anchor,rotated) : QLineF(rotated,anchor) );
}
}
void Line::mouseReleaseEvent( QGraphicsSceneMouseEvent * event ){
_dragIndex = -1;
QGraphicsLineItem::mouseReleaseEvent(event);
}
1- Overload mouseMoveEvent of your scene. Make sure you are in the initial state, no clicks, nothing. If position is close enough to the ends, set your flag as such.
// scene.cpp
void mouseMoveEvent(QMouseEvent *e){
if(moveToRotate){
lineItem->rotate(flag, e->pos());
...
return;
}
if(isClose(e->pos(), lineItem->firstEnd)
flag = 1;
else if(isClose(e->pos(), lineItem->secondEnd)
flag = 2;
else
flag = 0;
return;
}
2- Overload mouseClickEvent of the scene. If flag is set (1 or 2), get your anchor point. You can overload paint method of lineItem to highlight the end point. Also set firstClick flag.
void mouseClickEvent(QMouseEvent *e){ // firstClick happened
if(flag !=0){ //process click
firstClick = true;
paintAnchor = true;
moveToRotate = true;
}
else // neglect click
return;
return;
}
// myCustomLineItemclassThatInheritsQGraphicsLineItem.cpp
void paint(... ){
if(paintAnchor){
...
}
}
There are obvious errors, but the general flow should be as such. You may need a signal to connect the boolean to the paint event of another class. You may need to overload mouseReleaseEvent to properly set moveToRotate. And, of course rotate and isClose methods are yours to be written -maybe even exist in the API.
Just construct the main flowchart, it will help you a lot.

Resources