如何在使用C++的Qt中创建一个竖向(旋转)按钮

3

我希望在Qt中创建一个垂直按钮(使用C ++而不是Python),并将文本旋转90º,可以顺时针或逆时针方向。使用标准QPushButton似乎不可能实现。

我应该如何做呢?

1个回答

14
为了在Qt中创建一个垂直按钮,你可以子类化以便小部件报告的尺寸被转置,并修改绘图事件以使用正确的对齐方式绘制按钮。
这里有一个名为的类,可用作传统的即插即用替代品,但也支持通过使用进行垂直方向。 外观: Vertical button 示例用法:
auto anotherButton = new OrientablePushButton("Hello world world world world", this);
anotherButton->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Minimum);
anotherButton->setOrientation(OrientablePushButton::VerticalTopToBottom);

头文件:

class OrientablePushButton : public QPushButton
{
    Q_OBJECT
public:
    enum Orientation {
        Horizontal,
        VerticalTopToBottom,
        VerticalBottomToTop
    };

    OrientablePushButton(QWidget * parent = nullptr);
    OrientablePushButton(const QString & text, QWidget *parent = nullptr);
    OrientablePushButton(const QIcon & icon, const QString & text, QWidget *parent = nullptr);

    QSize sizeHint() const;

    OrientablePushButton::Orientation orientation() const;
    void setOrientation(const OrientablePushButton::Orientation &orientation);

protected:
    void paintEvent(QPaintEvent *event);

private:
    Orientation mOrientation = Horizontal;
};

源文件:

#include <QPainter>
#include <QStyleOptionButton>
#include <QDebug>
#include <QStylePainter>

OrientablePushButton::OrientablePushButton(QWidget *parent)
    : QPushButton(parent)
{ }

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

OrientablePushButton::OrientablePushButton(const QIcon &icon, const QString &text, QWidget *parent)
    : QPushButton(icon, text, parent)
{ }

QSize OrientablePushButton::sizeHint() const
{
    QSize sh = QPushButton::sizeHint();

    if (mOrientation != OrientablePushButton::Horizontal)
    {
        sh.transpose();
    }

    return sh;
}

void OrientablePushButton::paintEvent(QPaintEvent *event)
{
    Q_UNUSED(event);

    QStylePainter painter(this);
    QStyleOptionButton option;
    initStyleOption(&option);

    if (mOrientation == OrientablePushButton::VerticalTopToBottom)
    {
        painter.rotate(90);
        painter.translate(0, -1 * width());
        option.rect = option.rect.transposed();
    }

    else if (mOrientation == OrientablePushButton::VerticalBottomToTop)
    {
        painter.rotate(-90);
        painter.translate(-1 * height(), 0);
        option.rect = option.rect.transposed();
    }

    painter.drawControl(QStyle::CE_PushButton, option);
}

OrientablePushButton::Orientation OrientablePushButton::orientation() const
{
    return mOrientation;
}

void OrientablePushButton::setOrientation(const OrientablePushButton::Orientation &orientation)
{
    mOrientation = orientation;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接