Nesta página

QRubberBand Class

A classe QRubberBand fornece um retângulo ou uma linha que pode indicar uma seleção ou um limite. Mais...

Cabeçalho: #include <QRubberBand>
CMake: find_package(Qt6 REQUIRED COMPONENTS Widgets)
target_link_libraries(mytarget PRIVATE Qt6::Widgets)
qmake: QT += widgets
Herdado de: QWidget

Tipos públicos

enum Shape { Line, Rectangle }

Funções públicas

QRubberBand(QRubberBand::Shape s, QWidget *p = nullptr)
virtual ~QRubberBand()
void move(int x, int y)
void move(const QPoint &p)
void resize(int width, int height)
void resize(const QSize &size)
void setGeometry(const QRect &rect)
void setGeometry(int x, int y, int width, int height)
QRubberBand::Shape shape() const

Funções protegidas

virtual void initStyleOption(QStyleOptionRubberBand *option) const

Funções protegidas reimplementadas

virtual void changeEvent(QEvent *e) override
virtual bool event(QEvent *e) override
virtual void moveEvent(QMoveEvent *) override
virtual void paintEvent(QPaintEvent *) override
virtual void resizeEvent(QResizeEvent *) override
virtual void showEvent(QShowEvent *e) override

Descrição detalhada

Uma faixa elástica é frequentemente usada para indicar uma nova área de delimitação (como em um QSplitter ou um QDockWidget que está sendo desancorado). Historicamente, isso era implementado usando um QPainter e XOR, mas essa abordagem nem sempre funciona corretamente, já que a renderização pode ocorrer na janela abaixo da faixa elástica, mas antes que ela tenha sido “apagada”.

Você pode criar um QRubberBand sempre que precisar renderizar uma faixa elástica ao redor de uma determinada área (ou para representar uma única linha) e, em seguida, chamar setGeometry(), move() ou resize() para posicioná-la e definir seu tamanho. Um padrão comum é fazer isso em conjunto com eventos do mouse. Por exemplo:

void Widget::mousePressEvent(QMouseEvent *event)
{
    origin = event->pos();
    if (!rubberBand)
        rubberBand = new QRubberBand(QRubberBand::Rectangle, this);
    rubberBand->setGeometry(QRect(origin, QSize()));
    rubberBand->show();
}

void Widget::mouseMoveEvent(QMouseEvent *event)
{
    rubberBand->setGeometry(QRect(origin, event->pos()).normalized());
}

void Widget::mouseReleaseEvent(QMouseEvent *event)
{
    rubberBand->hide();
    // determine selection, for example using QRect::intersects()
    // and QRect::contains().
}

Se você passar um pai para o construtor do QRubberBand, a faixa elástica será exibida apenas dentro do pai, mas permanecerá sobre os outros widgets filhos. Se nenhum pai for passado, o QRubberBand atuará como um widget de nível superior.

Chame ` show()` para tornar a faixa elástica visível; isso também se aplica quando a faixa elástica não é de nível superior. Ocultar ou destruir o widget fará com que a faixa elástica desapareça. A faixa elástica pode ser um ` Rectangle ` ou um ` Line ` (vertical ou horizontal), dependendo do ` shape()` que foi passado a ela durante a construção.

Documentação do tipo de membro

enum QRubberBand::Shape

Esta enumeração especifica qual deve ser a forma de um objeto ` QRubberBand `. Trata-se de uma dica de desenho que é repassada ao sistema de estilos e pode ser interpretada por cada objeto ` QStyle`.

ConstanteValorDescrição
QRubberBand::Line0Um ` QRubberBand ` pode representar uma linha vertical ou horizontal. A geometria ainda é fornecida em ` rect()` e a linha preencherá a geometria fornecida na maioria dos estilos.
QRubberBand::Rectangle1Um ` QRubberBand ` pode representar um retângulo. Alguns estilos interpretarão isso como um retângulo preenchido (geralmente semitransparente) ou como um contorno retangular.

Documentação das funções-membro

[explicit] QRubberBand::QRubberBand(QRubberBand::Shape s, QWidget *p = nullptr)

Cria uma faixa elástica com a forma s, tendo como pai p.

Por padrão, uma faixa de seleção retangular (s é Rectangle) usa uma máscara, de modo que apenas uma pequena borda do retângulo fica visível. Alguns estilos (por exemplo, o nativo do macOS) alteram isso e chamam QWidget::setWindowOpacity() para criar um retângulo de seleção preenchido e semitransparente.

[virtual noexcept] QRubberBand::~QRubberBand()

Destrutor.

[override virtual protected] void QRubberBand::changeEvent(QEvent *e)

Reimplementa: QWidget::changeEvent(QEvent *event).

[override virtual protected] bool QRubberBand::event(QEvent *e)

Reimplementa: QWidget::event(QEvent *event).

[virtual protected] void QRubberBand::initStyleOption(QStyleOptionRubberBand *option) const

Inicialize ` option ` com os valores desta página: QRubberBand. Esse método é útil para subclasses quando elas precisam de um ` QStyleOptionRubberBand`, mas não querem preencher todas as informações por conta própria.

Veja também QStyleOption::initFrom().

void QRubberBand::move(int x, int y)

Mova o elástico para o ponto (x, y).

Veja também resize().

void QRubberBand::move(const QPoint &p)

Mova o elástico para o ponto p.

Esta é uma função sobrecarregada.

Veja também resize().

[override virtual protected] void QRubberBand::moveEvent(QMoveEvent *)

Reimplementa: QWidget::moveEvent(QMoveEvent *event).

[override virtual protected] void QRubberBand::paintEvent(QPaintEvent *)

Reimplementa: QWidget::paintEvent(QPaintEvent *event).

void QRubberBand::resize(int width, int height)

Redimensiona a faixa elástica de modo que sua largura seja width e sua altura seja height.

Veja também move().

void QRubberBand::resize(const QSize &size)

Redimensiona a faixa elástica de modo que seu novo tamanho seja size.

Esta é uma função sobrecarregada.

Veja também move().

[override virtual protected] void QRubberBand::resizeEvent(QResizeEvent *)

Reimplementa: QWidget::resizeEvent(QResizeEvent *event).

void QRubberBand::setGeometry(const QRect &rect)

Define a geometria da faixa elástica como ` rect`, especificada no sistema de coordenadas do widget pai.

Veja também QWidget::geometry.

void QRubberBand::setGeometry(int x, int y, int width, int height)

Define a geometria da faixa elástica como o retângulo cujo canto superior esquerdo está no ponto (x, y) e cujas dimensões são especificadas por width e height. A geometria é especificada no sistema de coordenadas do widget pai.

Esta é uma função sobrecarregada.

QRubberBand::Shape QRubberBand::shape() const

Retorna a forma desta faixa elástica. A forma só pode ser definida no momento da criação.

[override virtual protected] void QRubberBand::showEvent(QShowEvent *e)

Reimplementa: ` QWidget::showEvent(QShowEvent *event)`.

© 2026 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.