如果无法继承QSlider,如何在滑块上添加刻度线 [英] How to add a tick mark to a slider if it cannot inherit QSlider
问题描述
我有一个Qt对话框,其中有一个滑块,初始化对话框时,滑块将被设置一个值.为了提醒用户默认值,我想在滑块上添加一个标记,只需在手柄上方绘制一条线或一个三角形即可.在这里,滑块应为QSlider类型,这意味着我无法实现从QSlider派生的自定义控件.有什么办法可以实现吗?
I have a Qt dialog and there is a slider in it, when the dialog is initialized the slider will be set a value. In order to remind the user what is the default value, I want to add a mark to the slider, just draw a line or a triangle above the handle. Here, the slider should be of QSlider type, that means I can't implement a customized control derived from QSlider. Is there any way to realize it ?
推荐答案
我不清楚您为什么不能从QSlider
派生控件.您仍然可以将其视为QSlider
,只需重写paintEvent
方法即可.从视觉上来说,下面的示例很俗气,但是您可以使用QStyle
中的方法使其看起来更自然:
I'm not clear why you can't derive a control from QSlider
. You can still treat it like a QSlider
, just override the paintEvent
method. The example below is pretty cheesy, visually speaking, but you could use the methods from QStyle
to make it look more natural:
#include <QtGui>
class DefaultValueSlider : public QSlider {
Q_OBJECT
public:
DefaultValueSlider(Qt::Orientation orientation, QWidget *parent = NULL)
: QSlider(orientation, parent),
default_value_(-1) {
connect(this, SIGNAL(valueChanged(int)), SLOT(VerifyDefaultValue(int)));
}
protected:
void paintEvent(QPaintEvent *ev) {
int position = QStyle::sliderPositionFromValue(minimum(),
maximum(),
default_value_,
width());
QPainter painter(this);
painter.drawLine(position, 0, position, height());
QSlider::paintEvent(ev);
}
private slots:
void VerifyDefaultValue(int value){
if (default_value_ == -1) {
default_value_ = value;
update();
}
}
private:
int default_value_;
};
int main(int argc, char *argv[]) {
QApplication app(argc, argv);
DefaultValueSlider *slider = new DefaultValueSlider(Qt::Horizontal);
slider->setValue(30);
QWidget *w = new QWidget;
QVBoxLayout *layout = new QVBoxLayout;
layout->addWidget(slider);
layout->addStretch(1);
w->setLayout(layout);
QMainWindow window;
window.setCentralWidget(w);
window.show();
return app.exec();
}
#include "main.moc"
这篇关于如果无法继承QSlider,如何在滑块上添加刻度线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!