本文章主要学习QSlider样式
准备下面几张背景图片:
调小图标、调大图标、QSlider位置图标
QSlider划过的背景图标、QSlider未划过的背景图标
最终效果图
自己创建一个QSlider工程,此处省略……
编写mainwindow.h文件
1 #ifndef MAINWINDOW_H
2 #define MAINWINDOW_H
3
4 #include <QMainWindow>
5 #include <QSlider>
6 #include <QPushButton>
7
8
9 class MainWindow : public QMainWindow
10 {
11 Q_OBJECT
12
13 public:
14 explicit MainWindow(QWidget *parent = 0);
15 private slots:
16 void BtnLeftClick();
17 void BtnRightClick();
18 private:
19 QSlider *pQSlider;
20 };
21
22 #endif // MAINWINDOW_H
编写mainwindow.cpp文件
1 #include "mainwindow.h"
2
3 MainWindow::MainWindow(QWidget *parent) :
4 QMainWindow(parent)
5 {
6 this->resize(QSize(360,90));
7 this->setStyleSheet("background-color:rgb(43,45,55);border:none;");
8
9 QPushButton *pBtnL = new QPushButton(this);
10 QPushButton *pBtnR = new QPushButton(this);
11 pQSlider = new QSlider(Qt::Horizontal,this);
12
13 pBtnL->setGeometry(30,24,32,34);
14 pQSlider->setGeometry(70,20,220,40);
15 pBtnR->setGeometry(300,20,32,34);
16
17
18 pBtnL->setStyleSheet("outline:none;border-image: url(:/btn_del.png)");
19 pBtnR->setStyleSheet("outline:none;border-image: url(:/btn_add.png)");
20
21 //设置不可用,不可滑动
22 pQSlider->setEnabled(false);
23 pQSlider->setStyleSheet("QSlider::groove:horizontal{ \
24 height: 12px; \
25 left: 5px; \
26 right: 5px; \
27 border-image: url(:/qslider_bg.png);\
28 } \
29 QSlider::handle:horizontal{ \
30 border-radius: 20px; \
31 width: 40px; \
32 height: 40px; \
33 margin-top: -10px; \
34 margin-left: -10px; \
35 margin-bottom: -20px; \
36 margin-right: -10px; \
37 border-image:url(:/qslider_btn.png);} \
38 QSlider::sub-page:horizontal{border-image: url(:/qslider.png);}");
39
40
41 //设置最小值、最大值
42 pQSlider->setMinimum(0);
43 pQSlider->setMaximum(16);
44
45 //设置初始值
46 pQSlider->setValue(4);
47
48 //关联信号槽
49 connect(pBtnL,SIGNAL(clicked()),this,SLOT(BtnLeftClick()));
50 connect(pBtnR,SIGNAL(clicked()),this,SLOT(BtnRightClick()));
51 }
52
53 void MainWindow::BtnLeftClick()
54 {
55 if(pQSlider->value() > 0)
56 {
57 pQSlider->setValue(pQSlider->value()-1);
58 }
59 }
60
61 void MainWindow::BtnRightClick()
62 {
63 if(pQSlider->value() < 16)
64 {
65 pQSlider->setValue(pQSlider->value()+1);
66 }
67 }
编写main.cpp文件
1 #include "mainwindow.h"
2 #include <QApplication>
3
4 int main(int argc, char *argv[])
5 {
6 QApplication a(argc, argv);
7 MainWindow w;
8 w.show();
9
10 return a.exec();
11 }
es.qrc内容如下图所示