Qt Utilities  6.4.1
Common Qt related C++ classes and routines used by my applications such as dialogs, widgets and models
clearplaintextedit.cpp
Go to the documentation of this file.
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 
20 ClearPlainTextEdit::ClearPlainTextEdit(QWidget *parent)
21  : QPlainTextEdit(parent)
22  , ButtonOverlay(viewport())
23 {
24  handleCustomLayoutCreated();
26 }
27 
32 {
33 }
34 
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 
72 {
73  return document()->isEmpty();
74 }
75 
76 } // namespace QtUtilities
The ButtonOverlay class is used to display buttons on top of other widgets.
Definition: buttonoverlay.h:25
void updateClearButtonVisibility(bool visible)
Updates the visibility of the clear button.
QHBoxLayout * buttonLayout()
Returns the layout manager holding the buttons.
void setClearButtonEnabled(bool enabled)
Sets whether the clear button is enabled.
~ClearPlainTextEdit() override
Destroys the clear plain text edit.
bool isCleared() const override
Returns whether the related widget is cleared.