如何在 QT5.6.1 中创建自定义按钮 [英] How to Create Custom PushButton in QT5.6.1

查看:81
本文介绍了如何在 QT5.6.1 中创建自定义按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 QT 开发很陌生.任何人都可以分享如何在 QT 中创建自定义 QPushButton",以便自定义按钮将具有与 QPushButton 相同的行为,仅与自定义属性不同.因此,请对此提供任何线索或任何方向都会有所帮助.我已经尝试过 QT 自定义小部件示例中给出的模拟时钟示例.但我没有发现与 QPushbutton 相关.提前致谢.

I am very new to QT development. Can anyone share "How to create a custom QPushButton in QT" so that custom button will have same behavior as of QPushButton only differ from custom properties. So please any clue or any direction to this will be helpful. I have tried for the Analog Clock example which is given in QT custom widget example. But I didn't find related with QPushbutton. Thanks in advance.

推荐答案

很简单.首先你需要继承 QPushButton.添加您的方法以增强它.大功告成.

Its very simple. First you need to subclass QPushButton. Add your methods to enhance it. And you are done.

例如,我编写了 CustomButton,它有一个额外的方法来反转文本.

For example, I have written CustomButton which have an extra method to reverse the text.

自定义按钮.h

#ifndef CUSTOMBUTTON_H
#define CUSTOMBUTTON_H

#include <QPushButton>

class CustomButton : public QPushButton
{
public:
    CustomButton( const QString& text, QWidget* parent = 0 );

    // Enhancement, it will reverse the button text
    void reverseText();
};

#endif // CUSTOMBUTTON_H

自定义按钮.cpp

#include "CustomButton.h"
#include "algorithm"

CustomButton::CustomButton( const QString& text, QWidget* parent )
    : QPushButton( text, parent )
{

}

void CustomButton::reverseText()
{
    QString buttonText = text();
    std::reverse(buttonText.begin(), buttonText.end());
    setText( buttonText );
}

main.cpp

#include <QApplication>
#include "CustomButton.h"
int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    CustomButton w( "MyButton" );
    w.show();
    w.reverseText();
    a.exec();
    return 0;
}

按钮看起来像这样

如果你想做一些与外观和感觉相关的事情.您可以使用 QStyleSheet

If you want to do something related to look and feel. Instead of creating custom button you can use QStyleSheet

这篇关于如何在 QT5.6.1 中创建自定义按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆