简体   繁体   English

问:创建一个QDoubleSlider

[英]Qt: Creating a QDoubleSlider

I want to connect a QDoubleSpinBox with a QSlider like this: 我想一个连接QDoubleSpinBoxQSlider这样的:

QObject::connect(ui->myDoubleSpinBox, SIGNAL(valueChanged(double)), 
ui->mySlider, SLOT(setValue(double)));
    QObject::connect(ui->mySlider, SIGNAL(valueChanged(double)), 
ui->myDoubleSpinBox, SLOT(setValue(double)));

This won't work, for a QSlider only handles int values. 这不起作用,因为QSlider只处理int值。 So I think i need to add a custom slot to QSlider. 所以我想我需要为QSlider添加一个自定义插槽。
I thought about creating a new class derived from QSlider and then implementing the slot, like this: 我想创建一个从QSlider派生的新类,然后实现插槽,如下所示:

QDoubleSlider.hpp QDoubleSlider.hpp

#ifndef QDOUBLESLIDER_H
#define QDOUBLESLIDER_H

#include <QSlider>

class QDoubleSlider : public QSlider
{
    Q_OBJECT
public:
    explicit QDoubleSlider(QObject *parent = 0);

signals:

public slots:
    void setValue(double givenValue);
};

#endif // QDOUBLESLIDER_H


QDoubleSlider.cpp QDoubleSlider.cpp

#include "qdoubleslider.h"

QDoubleSlider::QDoubleSlider(QObject *parent) :
    QSlider(parent)
{
}

void QDoubleSlider::setValue(double givenValue)
{
    // code
}

Now I have two problems: 现在我有两个问题:

  1. The compiler complains about an invalid conversion from QObject* to QWidget* in the constructor. 编译器抱怨构造函数中从QObject*QWidget*转换无效。
  2. I don't know how setValue works and thus I don't even know how to implement that slot. 我不知道setValue是如何工作的,因此我甚至不知道如何实现该槽。

Any ideas? 有任何想法吗?

  1. parent needs to be a QWidget* , just as the error states parent必须是QWidget* ,正如错误所述
  2. Slots work like regular member functions. 插槽像常规成员函数一样工作。 You should probably store an exact double as a member and set the underlying slider to the appropriate integer equivalent. 您应该将精确的double存储为成员,并将基础滑块设置为适当的等效整数。 Remember to only send valueChanged signals if the value really changes. 请记住,如果值确实发生变化,则仅发送valueChanged信号。

Furthermore you should probably inherit from QWidget instead and have a QSlider as a child, as you do not want users of your class to change the integer range of your internal slider. 此外,您可能应该继承QWidget并将QSlider作为子项继承,因为您不希望类的用户更改内部滑块的整数范围。

  1. just simply replace your QObject to QWidget, because QSlider constructor is QSlider ( QWidget * parent = 0 ) 只需简单地将QObject替换为QWidget,因为QSlider构造函数是QSlider ( QWidget * parent = 0 )
  2. you'd better have a new slot named setDoubleValue(double givenValue) and connect to this slot. 你最好有一个名为setDoubleValue(double givenValue)的新插槽并连接到这个插槽。 in this slot, it is simple. 在这个插槽中,很简单。 like void QDoubleSlider::setDoubleValue(double givenValue) { setValue(static_cast<int>(givenValue)); } void QDoubleSlider::setDoubleValue(double givenValue) { setValue(static_cast<int>(givenValue)); } void QDoubleSlider::setDoubleValue(double givenValue) { setValue(static_cast<int>(givenValue)); }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM