1.使用系统自带api
QIcon myicon1;
myicon1.addFile(tr(":/image/Resource/new.png"));
ui->new_btn->setIcon(myicon1);
ui->new_btn->setIconSize(ui->new_btn->size());
//ui.btn_calib->setIconSize(QSize(90, 90));
ui->new_btn->setStyleSheet("background-color:rgba(0,0,0,0)");//透明背景
ui->new_btn->setFocusPolicy(Qt::NoFocus);
//设置按钮悬停事件
ui->new_btn->installEventFilter(this);//安装事件过滤器
效果为:
无法设置icon和文字之间的距离。
2.可使用QToolButton实现文字在图标下方
QIcon myicon9;
myicon9.addFile(tr(":/image/Resource/CAN_open.png"));
ui->openCan_toolButton->setIconSize(QSize(32,32));
ui->openCan_toolButton->setIcon(myicon9);
ui->openCan_toolButton->setText(tr("打开CAN"));
ui->openCan_toolButton->setToolButtonStyle(Qt::ToolButtonTextUnderIcon);
ui->openCan_toolButton->setStyleSheet("background-color:rgba(0,0,0,0)");
ui->openCan_toolButton->setFocusPolicy(Qt::NoFocus);
ui->openCan_toolButton->installEventFilter(this);//安装事件过滤器
效果为:
QToolButton与QPushButton并无大的区别,在常规使用二者很类似!
3.在pushbutton上面使用label进行布局
QLabel *iconLabel = new QLabel;
QLabel *textLabel = new QLabel;
iconLabel->setFixedSize(32,32);
iconLabel->setStyleSheet("border:1px solid red;");
textLabel->setStyleSheet("border:1px solid red;");
iconLabel->setPixmap(QPixmap(":/images/Setting.png"));
textLabel->setText(QString::fromLocal8Bit("系统设置"));
textLabel->setFixedWidth(60);
QHBoxLayout *myLayout = new QHBoxLayout();
myLayout->addSpacing(10);
myLayout->addWidget(iconLabel);
myLayout->addSpacing(30);
myLayout->addWidget(textLabel);
myLayout->addStretch();
ui->pushButton_2->setLayout(myLayout);
ui->pushButton_2->setStyleSheet("QPushButton{border:1px solid blue;background:white;}"
"QPushButton:hover{border:0px;background:blue;}"
"QPushButton:pressed{border:0px;background:red;}");
效果为:
4.使用图片,设置stylesheet
本小节参见:https://www.cnblogs.com/xj626852095/p/3648119.html
ui->test_btn->setStyleSheet("QPushButton{background-color:black;\
color: white; border-radius: 10px; border: 2px groove gray;\
border-style: outset;}"
"QPushButton:hover{background-color:white; color: black;}"
"QPushButton:pressed{background-color:rgb(85, 170, 255);\
border-style: inset; }");
以上4种方法,需要设置,比较麻烦,最好还是找UI设计按钮图片,这样软件的适配性也比较好。