| 1 | #include "./clearplaintextedit.h" |
| 2 | |
| 3 | #include <QHBoxLayout> |
| 4 | #include <QScrollBar> |
| 5 | #include <QStyle> |
| 6 | #include <QStyleOptionFrame> |
| 7 | |
| 8 | using namespace std; |
| 9 | |
| 10 | namespace QtUtilities { |
| 11 | |
| 12 | /*! |
| 13 | * \class ClearPlainTextEdit |
| 14 | * \brief A QPlainTextEdit with an embedded button for clearing its contents. |
| 15 | */ |
| 16 | |
| 17 | /*! |
| 18 | * \brief Constructs a clear plain text edit. |
| 19 | */ |
| 20 | ClearPlainTextEdit::ClearPlainTextEdit(QWidget *parent) |
| 21 | : QPlainTextEdit(parent) |
| 22 | , ButtonOverlay(viewport()) |
| 23 | { |
| 24 | handleCustomLayoutCreated(); |
| 25 | ButtonOverlay::setClearButtonEnabled(true); |
| 26 | } |
| 27 | |
| 28 | /*! |
| 29 | * \brief Destroys the clear plain text edit. |
| 30 | */ |
| 31 | ClearPlainTextEdit::~ClearPlainTextEdit() |
| 32 | { |
| 33 | } |
| 34 | |
| 35 | /*! |
| 36 | * \brief Updates the visibility of the clear button. |
| 37 | */ |
| 38 | void ClearPlainTextEdit::handleTextChanged() |
| 39 | { |
| 40 | updateClearButtonVisibility(!document()->isEmpty()); |
| 41 | } |
| 42 | |
| 43 | void ClearPlainTextEdit::handleClearButtonClicked() |
| 44 | { |
| 45 | // do no call clear() here to prevent clearing of undo history |
| 46 | QTextCursor cursor(document()); |
| 47 | cursor.select(QTextCursor::Document); |
| 48 | cursor.removeSelectedText(); |
| 49 | } |
| 50 | |
| 51 | void ClearPlainTextEdit::handleCustomLayoutCreated() |
| 52 | { |
| 53 | // set alignment to show buttons in the bottom right corner |
| 54 | ButtonOverlay::buttonLayout()->setAlignment(Qt::AlignBottom | Qt::AlignRight); |
| 55 | const QStyle *const s = style(); |
| 56 | QStyleOptionFrame opt; |
| 57 | opt.initFrom(this); |
| 58 | setContentsMarginsFromEditFieldRectAndFrameWidth(s->subElementRect(QStyle::SE_FrameContents, &opt, this), |
| 59 | s->pixelMetric(QStyle::PM_DefaultFrameWidth, &opt, m_widget), s->pixelMetric(QStyle::PM_LayoutVerticalSpacing, &opt, m_widget)); |
| 60 | connect(this, &QPlainTextEdit::textChanged, this, &ClearPlainTextEdit::handleTextChanged); |
| 61 | // ensure button layout is realigned when scrolling |
| 62 | connect(verticalScrollBar(), &QScrollBar::actionTriggered, this, &ClearPlainTextEdit::handleScroll); |
| 63 | connect(this, &QPlainTextEdit::cursorPositionChanged, this, &ClearPlainTextEdit::handleScroll); |
| 64 | } |
| 65 | |
| 66 | void ClearPlainTextEdit::handleScroll() |
| 67 | { |
| 68 | buttonLayout()->update(); |
| 69 | } |
| 70 | |
| 71 | bool ClearPlainTextEdit::isCleared() const |
| 72 | { |
| 73 | return document()->isEmpty(); |
| 74 | } |
| 75 | |
| 76 | } // namespace QtUtilities |