QWidget添加带有图片的QPushButton,布局QGridLayout

QWidget* w = new QWidget(this);

w->setGeometry(10,20,400,300);

QVBoxLayout* layout = new QVBoxLayout(w);

layout->setSpacing(0);

layout->setContentMargins(0,0,0,0);

QPushButton* b = new QPushButton(w);

b->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred);

layout->addWidget(b);

QString style = "QPushButton{image:url(:/normal.png);border-style:none;}

style += "QPushButton:hover{image:url(:/hover.png);border-style:none;}

style += "QPushButton:pressed{image:url(:/pressed.png);border-style:none;}

style += "QPushButton:checked{image:url(:/checked.png);border-style:none;}

b->setStyleSheet(style);

要想图片随着按钮大小拉伸,可以将image换成border-image

如果不想使用布局,自由设置按钮在widget中的位置:

QWidget* w = new QWidget(this);

w->setGeometry(10,20,400,300);

QPushButton* b = new QPushButton(w);

b->setGeometry(10,20,40,30);

b->show();//不要忘了这个,否则看不见

网格布局QGridLayout的使用

QGridLayout* g = new QGridLayout(w);

QPushButton* b1 = new QPushButton(w);b1->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred);

QPushButton* b2 = new QPushButton(w);b2->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred);

QPushButton* b3 = new QPushButton(w);b3->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred);

g->addWidget(b1,0,0,1,2);//占2行

g->addWidget(b2,0,1,1,1);

g->addWidget(b3,1,1,1,1);

原文地址:https://www.cnblogs.com/coolbear/p/11769960.html