Qt Creator使用css的入门小例子

Qt版本:qt5.6
点击文件——新建文件或项目——Application——Qt Widgets Application如下图:在这里插入图片描述
为自己的项目取个名字mycss2,如下图:
在这里插入图片描述
然后一路点击“下一步”最后确定。
然后右击左上角项目窗口中的“mycss2”项目——选择“添加新文件”——Qt——Qt Resource File,如下图:
在这里插入图片描述
然后为资源文件取个名字myResource,如下图:
在这里插入图片描述
然后我们在F:\QTCode\TestCode\myCss2\mycss2路径下新建一个res文件夹,然后用Notepad++软件新建一个文件,内容为

QPushButton{
    
    
border-style:none;
border:1px solid #242424;
color:#DCDCDC;
padding:5px;
min-height:15px;
border-radius:5px;
background:qlineargradient(spread:pad,x1:0,y1:0,x2:0,y2:1,stop:0 #484848,stop:1 #383838);
}

QPushButton:hover{
    
    
background:qlineargradient(spread:pad,x1:0,y1:0,x2:0,y2:1,stop:0 #646464,stop:1 #525252);
}

QPushButton:pressed{
    
    
background:qlineargradient(spread:pad,x1:0,y1:0,x2:0,y2:1,stop:0 #484848,stop:1 #383838);
}

编码格式为UTF-8,文件保存到路径F:\QTCode\TestCode\myCss2\mycss2\res,取名为style.css
然后回到qtCreator,右击myresource.qrc——添加现有文件——选择刚才新建的style.css文件。
然后在main.cpp的main函数中添加如下代码:

    QApplication a(argc, argv);
//设置样式表
    QFile styleSheet;
    styleSheet.setFileName(":/res/style.css");
    if(styleSheet.open(QFile::ReadOnly)) {
    
    
        QString styleString = styleSheet.readAll();
        styleSheet.close();
        static_cast<QApplication*>(QApplication::instance())->setStyleSheet(styleString);
    }
//设置样式表
    MainWindow w;
    w.show();
    return a.exec();

然后在mainwindow.ui上面拖个PushButton上去,如下图:
在这里插入图片描述
然后按F5编译运行,效果如下:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_43935474/article/details/105491913