自定义类的信号和插槽

时间:2012-06-21 09:30:19

标签: qt signals-slots qslider

我编写了一个自定义类来覆盖QSlider的seek方法。基本上这个类允许在用户点击的滑块上进行搜索。

tbslider.h

#ifndef TBSLIDER_H
#define TBSLIDER_H

#include <QSlider>
#include <QObject>

class Tbslider:  public QSlider
{
    Q_OBJECT
public:
    explicit Tbslider(QWidget *parent=0);

signals:
    void tbJump(int);
protected:
    void mousePressEvent(QMouseEvent *event);
private:
    QSlider *qslider;
};
#endif // TBSLIDER_H

tbslider.cpp

#include <iostream>
#include <QEvent>
#include <QPoint>
#include <QMouseEvent>
#include "tbslider.h"

Tbslider::Tbslider(QWidget *parent):QSlider(parent)
{

}
void Tbslider::mousePressEvent(QMouseEvent *event)
{
QSlider::mousePressEvent(event);

    std::cout<<"\nX co-ordinate"<<event->x();
    std::cout<<"\nY co-ordinate"<<event->y();
    int value =(minimum() + ((maximum()-minimum()) * event->x()) / width() ) ;
    setValue(value);
    emit tbJump(value);
}

main.cpp中的信号和插槽

  QApplication app(argc, argv);
  MainWindow player;
  Tbslider tbslider;
  GSTEngine listen
  app.connect(&tbslider, SIGNAL(tbJump(int)), &listen, SLOT(jump(int)));

以上代码应该有效。还有什么我需要做的吗?

1 个答案:

答案 0 :(得分:0)

该功能应该是

void Tbslider::mousePressEvent(QMouseEvent *event)
{


    std::cout<<"\nX co-ordinate"<<event->x();
    std::cout<<"\nY co-ordinate"<<event->y();
    int value =(minimum() + ((maximum()-minimum()) * event->x()) / width() ) ;
    setValue(value);
    emit tbJump(value); 
    QSlider::mousePressEvent(event);
}

在开头调用QSlider :: mousePressEvent(event)导致基类中的return语句。