Custom Linear QPushButton to Fit the Size of Its Parent
-
Hi all,
I'm writing an application that needs a linear and draggable widget to do some functions, like indicating some sizes of a picture, etc. This is what I want:
So I wrote:#include <QSizePolicy> #include <QWidget> #include <QPushButton> #include <QMouseEvent> class FloatingLine : public QPushButton { Q_OBJECT public: explicit FloatingLine(QWidget *parent = nullptr, Qt::Orientation orientation = Qt::Horizontal); protected: void mousePressEvent(QMouseEvent *event) override; void mouseMoveEvent(QMouseEvent *event) override; private: QPoint pressPoint; Qt::Orientation m_orientation; }; FloatingLine::FloatingLine(QWidget *parent, Qt::Orientation orientation) : QPushButton(parent) { setStyleSheet("background-color: rgb(0, 0, 0);"); m_orientation = orientation; if (m_orientation == Qt::Horizontal) { setMaximumHeight(3); setSizePolicy(QSizePolicy(QSizePolicy::Maximum, QSizePolicy::Fixed)); // Fill the width of its parent } else { setMaximumWidth(3); setSizePolicy(QSizePolicy(QSizePolicy::Fixed, QSizePolicy::Maximum)); } raise(); // Move to top } void FloatingLine::mousePressEvent(QMouseEvent *event) { if (event->button() == Qt::LeftButton) this->pressPoint = event->pos(); } void FloatingLine::mouseMoveEvent(QMouseEvent *event) { if (event->buttons() == Qt::LeftButton) { this->move(this->mapToParent(event->pos() - this->pressPoint)); // Avoid being moved out of parent if (this->mapToParent(this->rect().topLeft()).x() <= 0) { this->move(0, this->pos().y()); } if (this->mapToParent(this->rect().bottomRight()).x() >= this->parentWidget()->rect().width()) { this->move(this->parentWidget()->rect().width() - this->width(), this->pos().y()); } if (this->mapToParent(this->rect().topLeft()).y() <= 0) { this->move(this->pos().x(), 0); } if (this->mapToParent(this->rect().bottomRight()).y() >= this->parentWidget()->rect().height()) { this->move(this->pos().x(), this->parentWidget()->rect().height() - this->height()); } } } ........... FloatingLine *line { new FloatingLine(this, Qt::Horizontal) }; line->show(); ...........
However I got the result:
That is, the line(button) itself doesn't have the same width as its parent, which is not expected.
Is QSizePolicy not effective, or there another correct method?
Thanks. -
Hi,
There's no reason for a widget to "adopt" the size of its parent. Using layouts does that but it's not what you are after since you want to be able to move that widget.
If you want to adjust its size, you can do it in the resizeEvent from the parent for example. -
G Grit Clef has marked this topic as solved