我想创建一个具有以下属性的按钮
- 半透明的
- 自动换行
- 相对字体大小
- 当你点击按钮时,按钮的文本颜色和背景颜色改变
我可以用
单独实现这些半透明和颜色变化
button->setFlat(true);
button->setStyleSheet(
"QPushButton {"
"color: blue;"
"background-color: rgba(255, 255, 255, 90)"
"}"
"QPushButton:pressed {"
"color: lime;"
"background-color: rgba(255, 255, 255, 50)"
"}"
"QPushButton:flat {"
"border: none; "
"}"
);
换行:
QPushButton button;
QHBoxLayout layout;
button.setLayout(&layout);
QLabel label("LOOOOOOOOOOOOOOOOOONGGGGGGGGGGG TEXXXXXXXXXT");
label.setWordWrap(true);
layout.addWidget(&label);
button.show();
相对字体大小:
void MyButton::resizeEvent(QResizeEvent *event)
{
int pixelsHeight = this->size().height()/2;
if(pixelsHeight > 24) pixelsHeight = 24;
if(pixelsHeight < 8) pixelsHeight = 8;
m_font.setPixelSize(pixelsHeight);
label->setFont(m_font);
}
我怎样才能同时做到这一切?
我只是把你写的所有东西放在子类中。是你需要的吗?
* . h#ifndef MYBUTTON_H
#define MYBUTTON_H
#include <QPushButton>
#include <QLabel>
#include <QHBoxLayout>
#include <QResizeEvent>
class MyButton : public QPushButton
{
Q_OBJECT
public:
explicit MyButton(QWidget *parent = 0);
signals:
public slots:
protected:
void resizeEvent(QResizeEvent *event);
private:
QLabel * label;
QFont *m_font;
};
#endif // MYBUTTON_H
* . cpp#include "mybutton.h"
MyButton::MyButton(QWidget *parent) :
QPushButton(parent)
{
setFlat(true);
setStyleSheet(
"QPushButton {"
"color: blue;"
"background-color: rgba(255, 255, 255, 90)"
"}"
"QPushButton:pressed {"
"color: lime;"
"background-color: rgba(255, 255, 255, 50)"
"}"
"QPushButton:flat {"
"border: none; "
"}"
);
QHBoxLayout *layout = new QHBoxLayout;
setLayout(layout);
label = new QLabel("LOOOOOOOOOOOOOOOOOONGGGGGGGGGGG TEXXXXXXXXXT",this);
label->setWordWrap(true);
layout->addWidget(label);
m_font = new QFont();
}
void MyButton::resizeEvent(QResizeEvent *event)
{
int pixelsHeight = this->size().height()/2;
if(pixelsHeight > 24) pixelsHeight = 24;
if(pixelsHeight < 8) pixelsHeight = 8;
m_font->setPixelSize(pixelsHeight);
label->setFont(*m_font);
}
main.cpp
#include "mybutton.h"
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MyButton but;
but.show();
return a.exec();
}