如何在QT中创建具有多个属性的按钮

  • 本文关键字:属性 按钮 QT 创建 c++ qt qt5
  • 更新时间 :
  • 英文 :


我想创建一个具有以下属性的按钮

  1. 半透明的
  2. 自动换行
  3. 相对字体大小
  4. 当你点击按钮时,按钮的文本颜色和背景颜色改变

我可以用

单独实现这些

半透明和颜色变化

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();
}

相关内容

  • 没有找到相关文章

最新更新