[QT笔记]用图片自定义QCheckBox样式

来源:互联网 发布:网易邮箱服务器域名 编辑:程序博客网 时间:2024/06/04 18:30

记录一下大致的过程,避免将来忘记。


实现环境:Qt Creator 3.2.1 Based on Qt5.3.2 (GCC 4.9.2, 32bit)

项目类型:Qt Widgets Application

1.首先在项目中添加Qt资源文件,命名为resource.qrc。

2.然后在资源文件中添加前缀,默认是/new/prefix1,我将它改为/CheckBox。

3.然后向/CheckBox中添加文件checked.png、uncheked.png、checkedDisabled.png。

添加文件时,选中某个项目文件夹以外路径下的图片后,会提示“无效的文件路径,文件/***/***/checked.png 没有在资源文件的子目录中,您可以选择此文件到一个有效的路径”。此时选择“复制”,将图片复制到项目文件夹下。可以在项目文件夹里面创建文件夹res,进入该文件夹后,选择“保存”。之后也是将图片保存到res文件夹下。

4.在文件管理器中打开项目文件夹下的res文件夹,新建"myStyle.qss"文件,用文本编辑器打开,填写以下内容然后保存:

QCheckBox{    spacing: 5px;}QCheckBox::indicator{    width: 15px;    height: 15px;}QCheckBox::indicator:unchecked{    image:url(:/CheckBox/res/unchecked.png);}QCheckBox::indicator:checked{    image:url(:/CheckBox/res/checked.png);}QCheckBox::indicator:checked:disabled{    image:url(:/CheckBox/res/checkedDisabled.png);}

5.在/CheckBox前缀中添加myStyle.qss文件,这一次不必复制到项目文件夹下,因为它已经在项目文件夹下了。

6.保存资源文件resource.qrc。

7.接着在main.cpp文件中添加代码,读取qss文件并设置程序为自定义的样式:

int main(int argc, char *argv[]){    QApplication a(argc, argv);    //获取并设置程序为自定义样式    QFile styleSheet(":/CheckBox/res/myStyle.qss");    styleSheet.open(QIODevice::ReadOnly);    a.setStyleSheet(styleSheet.readAll());    MainWindows w;    w.show();     return a.exec();}

8.然后可以在程序中添加CheckBox查看效果:



9.QCheckBox可以支持自定义的效果还有很多,以下是Qt Style Sheets Examples当中关于QCheckBox样式的示例:

QCheckBox {    spacing: 5px;} QCheckBox::indicator {    width: 13px;    height: 13px;} QCheckBox::indicator:unchecked {    image: url(:/images/checkbox_unchecked.png);} QCheckBox::indicator:unchecked:hover {    image: url(:/images/checkbox_unchecked_hover.png);} QCheckBox::indicator:unchecked:pressed {    image: url(:/images/checkbox_unchecked_pressed.png);} QCheckBox::indicator:checked {    image: url(:/images/checkbox_checked.png);} QCheckBox::indicator:checked:hover {    image: url(:/images/checkbox_checked_hover.png);} QCheckBox::indicator:checked:pressed {    image: url(:/images/checkbox_checked_pressed.png);} QCheckBox::indicator:indeterminate:hover {    image: url(:/images/checkbox_indeterminate_hover.png);} QCheckBox::indicator:indeterminate:pressed {    image: url(:/images/checkbox_indeterminate_pressed.png);}

扩展阅读:Qt Style Sheet实践(三):QCheckBox和QRadioButton



0 0
原创粉丝点击