我一直在组合一个图像滑块,根据一些按钮动画图像。作为我正在寻找的效果的示例,请参阅此页面的顶部(http://www.menucool.com/slider/javascript-image-slider-demo4)。
通过继承QObject / QGraphicsItemGroup(在imageSlider.h和imageSlider.cpp中编码)并向其添加动画,我在这部分过程中取得了成功。该代码可能对尝试类似的其他人有用。
接下来我想添加点击imageSlider的功能,它会发出clicked()信号,从而可以查询所选图像并根据该选择执行某些任务。听起来很容易。
尝试1:
我的第一个也许是最明显的尝试是重新实现imageSlider中的mouseReleaseEvent处理程序以捕获鼠标点击。但是,这个函数永远不会被调用。
尝试2:
将imageSlider添加到QGraphicsScene,然后通过QGraphicsView查看。有意义的是,QGraphicsView可能正在处理鼠标点击,因此它们根本没有进入imageSlider。所以我将QGraphicsView子类化为一个名为clickableQGraphicsView的类,它有一个重新实现的mouseReleaseEvent。 这确实有效。虽然我可以使用这种方法继续前进,但为了优雅起见,我想将与imageSlider交互所需的所有代码封装到imageSlider代码本身中。如果我使用这种方法,则需要两个类。
尝试5:(尝试3& 4无法解决)
我认为可以将常规QGraphicsView检测到的事件传递给imageSlider中的事件处理程序。这意味着我可以使用标准的QGraphicsView class并且有能力在imageSlider中检测自己的鼠标点击。我安装了事件过滤器。 imageSlider中的此事件处理程序在QGraphicsView中的鼠标移动时被调用,因此过滤器似乎可以工作。然而,奇怪的是,未检测到鼠标点击事件。
所以,问题是:
我确定你想知道我为什么不闭嘴并使用尝试2.然而我很好奇,我对自己的教育感兴趣,因为尝试1和5的原因不是工作。
最简单的测试方法是从下载项目代码: https://www.dropbox.com/sh/zxlo3n014v7g2n7/riMq3FCB4i 专业文件位于TestGUI文件夹中。
可以通过更改imageSlider.h顶部的#define来编译各种尝试。如果所有定义都已注释掉,则不会启用任何单击检测。可以通过取消注释相应的#define行来测试每个尝试。
如果愿意,受影响的代码会粘贴在下面。
imageSlider.h 代码也显示如下:
class imageSlider: public QObject, public QGraphicsItemGroup
{
Q_OBJECT
Q_PROPERTY(QPointF pos READ pos WRITE setPos) /// these property access functions don't have to be reimplemented as they are implemented in QObject. Just declare them.
public:
imageSlider(QGraphicsItem *parent = 0);
~imageSlider();
virtual void addToGroup(QGraphicsItem *item); // /virtual function is used so that the function can be reimplemented but using the same signature (name, arguments, etc)
virtual void removeFromGroup(QGraphicsItem *item);
void moveImage(int numImages);
void setTransitionDuration(uint ms);
void setEasingCurve(uint curveNum); //see the help file for QEasingCurve to see what the integers stand for
private:
QList <QGraphicsItem*> items; /// holds the images themselves
uint transitionDuration; /// The duration of the transition in ms
int currentImageIndex; /// The index of the currently displayed image
QMutex animationMutexLock; /// So that an animation cannot be called while the previous one is ongoing
QEasingCurve::Type easingCurveType; /// the type of easing curve for the animation.
int getXPosChange(int numImages); /// Get the amount the position has to change by to slide by numImages images
void animate(int xPosChange); /// Move the images along by the number of pixels in xPosChange
public slots:
void unlockMutex();
signals:
void clicked(); /// Parent process can be connected to this. When clicked the getCurrentImageIndex() function can be called and a response carried out (like running a process, opening a link, etc).
//*******************
// TEST CODE
//*******************
#ifdef MOUSECLICKDETECTATTEMPT1
public slots:
void mouseReleaseEvent(QGraphicsSceneMouseEvent * event);
#endif
#ifdef MOUSECLICKDETECTATTEMPT5
protected:
bool eventFilter(QObject *target, QEvent *event);
#endif
};
imageSlider.cpp 是:
#include "imageSlider.h"
/**
* Constructor for image slider.
*/
imageSlider::imageSlider(QGraphicsItem *parent) :
QObject(0),
QGraphicsItemGroup(parent),
transitionDuration(500),
currentImageIndex(0),
easingCurveType(QEasingCurve::Linear)
{
}
/**
* Deconstructor for image slider.
*/
imageSlider::~imageSlider()
{
if(~items.isEmpty())
items.clear();
}
/**
* Add QGraphicsItems (images from QPixmaps) to the image slider.
*/
void imageSlider::addToGroup(QGraphicsItem *item){
//change the xpos of the item before adding so that the images line up one after the other
int xpos = 0;
for(int i=0;i<items.count();i++)
xpos += items.at(i)->boundingRect().width();
item->setX(xpos);
//add to the items and group
items << item;
QGraphicsItemGroup::addToGroup(item);
}
/**
* Remove items from the imageSlider.
*/
void imageSlider::removeFromGroup(QGraphicsItem *item)
{
items.removeAll(item);
QGraphicsItemGroup::removeFromGroup(item);
}
/**
* Move the imageSlider along by numImages number of images.
* numImages can be +ve (move images left) or -ve (move images right).
*/
void imageSlider::moveImage(int numImages)
{
if(animationMutexLock.tryLock()) //the mutex will be unlocked on receiving the finished() signal from the animation object
{
int xPosChange = getXPosChange(numImages);
if(xPosChange==0) //not going to move, so unlock the mutex here as otherwise you have to wait for a zero move animation to finish before getting the next animation. Not a bug, but not ideal for user fluidity.
animationMutexLock.unlock();
else
//Do the animation
imageSlider::animate(xPosChange);
}
}
/**
* Calculate the distance the QGraphicsItemGroup must slide to show the rqeuired image.
* A positive numImages move moves the current image to the left.
* A negative numImages move moves the current image to the right.
*/
int imageSlider::getXPosChange(int numImages)
{
//create an incrementer that increments up or down to the requested image
int incrementer = 1;
if(numImages<0)
incrementer = -1;
int imageToGoTo = currentImageIndex + numImages;
//check that the requested image is within the bounds of the number of images we have
if(imageToGoTo<0)
imageToGoTo = 0;
if(imageToGoTo>items.count()-1)
imageToGoTo = items.count()-1;
//calculate the positional change
int posChange = 0;
int i=0;
for(i=currentImageIndex;i!=imageToGoTo;i+=incrementer)
posChange += items.at(i)->boundingRect().width(); //add the width of each image to skip over
//update the current image index to the image that will be shown
currentImageIndex = imageToGoTo;
//if we want to move to the right, make the positional change negative
if(incrementer==1)
posChange = -posChange;
return posChange;
}
/**
* Carry out the animation from one image to another.
*/
void imageSlider::animate(int xPosChange)
{
QPointF currPos = this->pos();
QPointF endPos = currPos;
endPos.setX(currPos.x()+xPosChange);
QPropertyAnimation *animation = new QPropertyAnimation(this,"pos");
connect(animation,SIGNAL(finished()),SLOT(unlockMutex()));
animation->setStartValue(currPos);
animation->setEndValue(endPos);
animation->setDuration(this->transitionDuration);
animation->setEasingCurve(this->easingCurveType);
animation->start(QAbstractAnimation::DeleteWhenStopped);
}
/**
* A slot which is called when the animation is completed to unlock the mutex.
* This mutex stops two animations from occurring at the same time.
*/
void imageSlider::unlockMutex()
{
this->animationMutexLock.unlock();
}
/**
* set function for the animation transition duration.
*/
void imageSlider::setTransitionDuration(uint ms)
{
this->transitionDuration = ms;
}
/**
* set functionfor the easing curve enum.
*/
void imageSlider::setEasingCurve(uint curveNum)
{
this->easingCurveType = (QEasingCurve::Type)curveNum;
}
//*******************
// TEST CODE
//*******************
#ifdef MOUSECLICKDETECTATTEMPT1
/**
* Try reimplementing the mouseReleaseEvent for the imageSlider to catch mouse clicks.
*/
void imageSlider::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
{
qDebug() << "imageSlider mouse release event detected";
emit clicked();
}
#endif
#ifdef MOUSECLICKDETECTATTEMPT5
/**
* Try capturing clicks on the images within the slider using a QObject event filter (imageSlider inherits from QObject and QGraphicsItemGroup.
*/
bool imageSlider::eventFilter(QObject *target, QEvent *event)
{
if(event->type()==QEvent::MouseButtonRelease)
{
qDebug() << "imageSlider mouse release event detected through the eventFilter";
emit clicked();
return true;
}
return false;
}
#endif
主表单代码 mainWindow.h 是:
//
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QGraphicsScene>
#include <QGraphicsItem>
#include <QPropertyAnimation>
#include "../imageSlider/imageSlider.h"
#include <QGraphicsView>
namespace Ui {
class MainWindow;
}
#ifdef MOUSECLICKDETECTATTEMPT2
class clickableQGraphicsView : public QGraphicsView
{
Q_OBJECT
public:
clickableQGraphicsView(QWidget *parent=0);
~clickableQGraphicsView();
public slots:
virtual void mouseReleaseEvent(QMouseEvent *event);
};
#endif
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
private slots:
void on_pushButtonRight_clicked();
void on_pushButtonLeft_clicked();
void on_listWidgetAnimType_currentTextChanged(const QString ¤tText);
void on_spinBoxMSAnim_valueChanged(int arg1);
void imageGroupClicked();
private:
Ui::MainWindow *ui;
imageSlider *imageGroup;
QGraphicsScene *GScene;
void moveImageSlider(int numImages);
//****************
// TEST CODE
//****************
#ifdef MOUSECLICKDETECTATTEMPT2
clickableQGraphicsView *clickView;
#endif
};
#endif // MAINWINDOW_H
最后, mainWindow.cpp 是:
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "qmessagebox.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
//*******************
// Set up options list
// for animation types
//*******************
for(int i=0;i<41;i++)
ui->listWidgetAnimType->addItem(QString::number(i));
//****************
// Graphics Scene
//****************
QPixmap pixmap1(":imageSwipe/images/1.png");
QGraphicsItem *Image1 = new QGraphicsPixmapItem(pixmap1);
QPixmap pixmap2(":imageSwipe/images/2.png");
QGraphicsItem *Image2 = new QGraphicsPixmapItem(pixmap2);
QPixmap pixmap3(":imageSwipe/images/3.png");
QGraphicsItem *Image3 = new QGraphicsPixmapItem(pixmap3);
QPixmap pixmap4(":imageSwipe/images/4.png");
QGraphicsItem *Image4 = new QGraphicsPixmapItem(pixmap4);
GScene = new QGraphicsScene();
GScene->setSceneRect(QRectF(0,0,Image1->boundingRect().width(),Image1->boundingRect().height()));
imageGroup = new imageSlider;
imageGroup->addToGroup(Image1);
imageGroup->addToGroup(Image2);
imageGroup->addToGroup(Image3);
imageGroup->addToGroup(Image4);
GScene->addItem(imageGroup);
ui->graphicsViewGUIInterface->setScene(GScene);
ui->graphicsViewGUIInterface->setGeometry(0,0,Image1->boundingRect().width(),Image1->boundingRect().height());
//*******************
// TEST CODE
//*******************
connect(imageGroup,SIGNAL(clicked()),this,SLOT(imageGroupClicked()));
#ifdef MOUSECLICKDETECTATTEMPT2
clickView = new clickableQGraphicsView(this);
clickView->setScene(GScene);
clickView->setGeometry(20,20,Image1->boundingRect().width(),Image1->boundingRect().height());
#endif
#ifdef MOUSECLICKDETECTATTEMPT5
ui->graphicsViewGUIInterface->installEventFilter(imageGroup);
#endif
}
MainWindow::~MainWindow()
{
if(imageGroup)
{
disconnect(imageGroup);
delete imageGroup;
}
if(GScene)
delete GScene;
delete ui;
}
void MainWindow::on_pushButtonRight_clicked()
{
moveImageSlider(-1);
}
void MainWindow::on_pushButtonLeft_clicked()
{
moveImageSlider(1);
}
void MainWindow::moveImageSlider(int numImages)
{
imageGroup->moveImage(numImages);
}
void MainWindow::on_listWidgetAnimType_currentTextChanged(const QString ¤tText)
{
imageGroup->setEasingCurve(currentText.toUInt());
}
void MainWindow::on_spinBoxMSAnim_valueChanged(int arg1)
{
imageGroup->setTransitionDuration((uint)arg1);
}
void MainWindow::imageGroupClicked()
{
QMessageBox msgBox;
msgBox.setText(QString("Received index = 1"));
msgBox.exec();
}
//***************
// TEST CODE
//***************
#ifdef MOUSECLICKDETECTATTEMPT2
/**
* The below functions are an attempt to subclass the QGraphicsView
* to provide a click response.
*/
clickableQGraphicsView::clickableQGraphicsView(QWidget *parent) :
QGraphicsView(parent)
{
}
clickableQGraphicsView::~clickableQGraphicsView()
{
}
void clickableQGraphicsView::mouseReleaseEvent(QMouseEvent *event)
{
if(event->type() == QEvent::MouseButtonRelease)
qDebug() << "QGraphicsView event dectected";
}
#endif
感谢您的帮助。我希望这对其他人也有用。 斯蒂芬
答案 0 :(得分:1)
好的我对提到的对象的确不太熟悉,但也许只是彻底阅读手册并进行一些调试就足够了。我们来看看:
1)我首先要注意的是,在not
值上使用二进制bool
有点反直觉而且不是一个好习惯,我的VS甚至向我发出警告。我的意思是确切地说这一行:if(~items.isEmpty())
。
2)当你进入QGraphicsItem::mouseReleaseEvent
的Qt手册时,你会发现这些行:
请注意,mousePressEvent()决定接收鼠标事件的图形项。有关详细信息,请参阅mousePressEvent()说明。
所以我们要QGraphicsItem::mousePressEvent
我们发现的是:
鼠标按下事件决定哪个项目应成为鼠标抓取器(请参阅QGraphicsScene :: mouseGrabberItem())。如果您不重新实现此功能,则按下事件将传播到此项目下方的任何最顶层项目,并且不会将任何其他鼠标事件传递到此项目。
所以基本上要解决第一次尝试的问题我们只需覆盖mousePressEvent
,功能无效{}
,事件将进入mouseReleaseEvent
imageSlider
3)关于方法5,有点难以弄清楚。基本上由于QGraphicsView的特殊性质而无效 - 它总是将QEvent::MouseButtonRelease
类型的事件转换为它的特殊QEvent::GraphicsSceneMouseRelease
类型并将其发送给它的鼠标抓取器(前面提到过),但即使没有'在任何这些鼠标抓取器中,它仍然将GraphicsSceneMouseRelease
事件设置为已接受,因此MouseButtonRelease
也被接受,因此最终它永远不会被发送到eventFilter
。顺便说一下,MousePressEvent
没有被这样吃掉。
实际上使用setEventFilter
在大多数情况下都是通用的方式,所以无论如何我猜你应该坚持先提到的方式。