这是最终的效果:
只有一个文件,直接可以编译运行
说明一点::
需要隐藏scrollbar的边框来消除QWidget赋予它的自带的黑色填充
#include <QListView>
#include <QApplication>
#include <QHBoxLayout>
#include <QScrollBar>
#include <QPainter>
#include <QStringListModel>
class VScrollBar:public QScrollBar
{
public:
VScrollBar(){}
protected:
void paintEvent(QPaintEvent* e){
qreal pos = this->value() * 1.0 / this->maximum();
int x = width();
const int w = x - 2;
int y = height();
QPainter p(this);
p.setRenderHints(QPainter::Antialiasing );
QPen pen;
pen.setColor("black");
p.setPen(pen);
//draw a line
p.drawRoundedRect(QRectF(x/2-1,20,2,y - 40),1,1); // draw a line
int _y = (y-40-w) * pos;
p.setBrush(QBrush("gray"));
//draw a knob
pen.setWidth(2);
p.drawRoundedRect(QRectF((x-w)/2,_y+20,w,w),w,w);
}
};
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
auto * w = new QWidget;
//设置白色的背景
w->setPalette(QPalette("","white","","","","",""));
auto * list = new QListView;
//隐藏丑陋的边框
list->setStyleSheet("border:none;");
list->setVerticalScrollBar(new VScrollBar);
auto * m = new QStringListModel;
m->setStringList(QColor::colorNames());
list->setModel(m);
auto * mainLayout = new QHBoxLayout;
mainLayout->addWidget(list);
w->setLayout(mainLayout);
w->show();
return a.exec();
}