QGIS API Documentation 3.41.0-Master (45a0abf3bec)
Loading...
Searching...
No Matches
qgstexteditwrapper.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgstexteditwrapper.cpp
3 --------------------------------------
4 Date : 5.1.2014
5 Copyright : (C) 2014 Matthias Kuhn
6 Email : matthias at opengis dot ch
7 ***************************************************************************
8 * *
9 * This program is free software; you can redistribute it and/or modify *
10 * it under the terms of the GNU General Public License as published by *
11 * the Free Software Foundation; either version 2 of the License, or *
12 * (at your option) any later version. *
13 * *
14 ***************************************************************************/
15
16#include "qgstexteditwrapper.h"
17#include "moc_qgstexteditwrapper.cpp"
18
19#include "qgsfields.h"
20#include "qgsfieldvalidator.h"
21#include "qgsfilterlineedit.h"
22#include "qgsapplication.h"
23#include "qgsjsonutils.h"
24#include "qgsmessagebar.h"
25#include "qgslogger.h"
26
27#include <QSettings>
28#include <nlohmann/json.hpp>
29
30QgsTextEditWrapper::QgsTextEditWrapper( QgsVectorLayer *layer, int fieldIdx, QWidget *editor, QWidget *parent )
31 : QgsEditorWidgetWrapper( layer, fieldIdx, editor, parent )
32
33{
34}
35
37{
38 QString v;
39
40 if ( mTextEdit )
41 {
42 if ( config( QStringLiteral( "UseHtml" ) ).toBool() )
43 {
44 if ( mTextEdit->toPlainText().isEmpty() )
45 {
46 v = QString();
47 }
48 else
49 {
50 v = mTextEdit->toHtml();
51 }
52 }
53 else
54 {
55 v = mTextEdit->toPlainText();
56 }
57 }
58
59 if ( mPlainTextEdit )
60 {
61 v = mPlainTextEdit->toPlainText();
62 }
63
64 if ( mLineEdit )
65 {
66 v = mLineEdit->text();
67 }
68
69 if ( ( v.isEmpty() && ( field().type() == QMetaType::Type::Int
70 || field().type() == QMetaType::Type::Double
71 || field().type() == QMetaType::Type::LongLong
72 || field().type() == QMetaType::Type::QDate ) )
74 {
76 }
77
78 if ( !QgsVariantUtils::isNull( defaultValue() ) && v == defaultValue().toString() )
79 {
80 return defaultValue();
81 }
82
83 QVariant res( v );
84 // treat VariantMap fields including JSON differently
85 if ( field().type() != QMetaType::Type::QVariantMap && field().convertCompatible( res ) )
86 {
87 return res;
88 }
89 else if ( field().type() == QMetaType::Type::QString && field().length() > 0 )
90 {
91 // for string fields convertCompatible may return false due to field length limit - in this case just truncate
92 // input rather then discarding it entirely
93 return QVariant( v.left( field().length() ) );
94 }
95 else if ( field().type() == QMetaType::Type::QVariantMap )
96 {
97 // replace empty string (invalid) with quoted empty string
98 if ( v.isEmpty() )
99 {
100 QVariant qjson = QgsJsonUtils::parseJson( std::string( "\"\"" ) );
101 mInvalidJSON = false;
102 return qjson;
103 }
104 if ( json::accept( v.toStdString() ) )
105 {
106 QVariant qjson = QgsJsonUtils::parseJson( v.toStdString() );
107 mInvalidJSON = false;
108 return qjson;
109 }
110 else
111 // return null value if json is invalid
112 {
113 if ( v.length() > 0 )
114 {
115 mInvalidJSON = true;
116 }
117 else
118 {
119 mInvalidJSON = false;
120 }
121 return QVariant();
122 }
123 }
124 else
125 {
126 return QgsVariantUtils::createNullVariant( field().type() );
127 }
128}
129
130QWidget *QgsTextEditWrapper::createWidget( QWidget *parent )
131{
132 mForm = qobject_cast<QgsAttributeForm *>( parent );
133 if ( config( QStringLiteral( "IsMultiline" ) ).toBool() )
134 {
135 if ( config( QStringLiteral( "UseHtml" ) ).toBool() )
136 {
137 return new QTextBrowser( parent );
138 }
139 else
140 {
141 return new QPlainTextEdit( parent );
142 }
143 }
144 else
145 {
146 return new QgsFilterLineEdit( parent );
147 }
148}
149
150void QgsTextEditWrapper::initWidget( QWidget *editor )
151{
152 mInvalidJSON = false;
153 mTextBrowser = qobject_cast<QTextBrowser *>( editor );
154 mTextEdit = qobject_cast<QTextEdit *>( editor );
155 mPlainTextEdit = qobject_cast<QPlainTextEdit *>( editor );
156 mLineEdit = qobject_cast<QLineEdit *>( editor );
157
158 if ( mTextEdit )
159 connect( mTextEdit, &QTextEdit::textChanged, this, &QgsEditorWidgetWrapper::emitValueChanged );
160
161 if ( mPlainTextEdit )
162 connect( mPlainTextEdit, &QPlainTextEdit::textChanged, this, &QgsEditorWidgetWrapper::emitValueChanged );
163
164 if ( mLineEdit )
165 {
166 mLineEdit->setValidator( new QgsFieldValidator( mLineEdit, field(), defaultValue().toString() ) );
167
168 QVariant defVal = defaultValue();
169 if ( QgsVariantUtils::isNull( defVal ) )
170 {
172 }
173
174 QgsFilterLineEdit *fle = qobject_cast<QgsFilterLineEdit *>( mLineEdit );
175 if ( field().type() == QMetaType::Type::Int || field().type() == QMetaType::Type::Double || field().type() == QMetaType::Type::LongLong || field().type() == QMetaType::Type::QDate )
176 {
177 mPlaceholderText = defVal.toString();
178 mLineEdit->setPlaceholderText( mPlaceholderText );
179 }
180 else if ( fle )
181 {
182 fle->setNullValue( defVal.toString() );
183 }
184
185 connect( mLineEdit, &QLineEdit::textChanged, this, [ = ]( const QString & value )
186 {
188 emit valueChanged( value );
190 emit valuesChanged( value );
191 } );
192 connect( mLineEdit, &QLineEdit::textChanged, this, &QgsTextEditWrapper::textChanged );
193 }
194}
195
197{
198 return mLineEdit || mTextEdit || mPlainTextEdit;
199}
200
202{
203 if ( mTextEdit )
204 mTextEdit->blockSignals( true );
205 if ( mPlainTextEdit )
206 mPlainTextEdit->blockSignals( true );
207 if ( mLineEdit )
208 {
209 mLineEdit->blockSignals( true );
210 // for indeterminate state we need to clear the placeholder text - we want an empty line edit, not
211 // one showing the default value (e.g., "NULL")
212 mLineEdit->setPlaceholderText( QString() );
213 }
214
215 //note - this is deliberately a zero length string, not a null string!
216 setWidgetValue( QLatin1String( "" ) ); // skip-keyword-check
217
218 if ( mTextEdit )
219 mTextEdit->blockSignals( false );
220 if ( mPlainTextEdit )
221 mPlainTextEdit->blockSignals( false );
222 if ( mLineEdit )
223 mLineEdit->blockSignals( false );
224}
225
227{
228 // Do nothing if the value has not changed
229 if ( mInvalidJSON )
230 mForm->displayWarning( tr( "Your JSON was invalid and has been reverted back to the last valid edit or the original data" ) );
231 {
232 mInvalidJSON = false;
233 }
234 setFormFeature( feature );
235 setValue( feature.attribute( fieldIdx() ) );
236}
237
238void QgsTextEditWrapper::updateValues( const QVariant &val, const QVariantList & )
239{
240 if ( mLineEdit )
241 {
242 //restore placeholder text, which may have been removed by showIndeterminateState()
243 mLineEdit->setPlaceholderText( mPlaceholderText );
244 }
245 setWidgetValue( val );
246}
247
249{
250 if ( mTextEdit )
251 mTextEdit->setReadOnly( !enabled );
252
253 if ( mPlainTextEdit )
254 mPlainTextEdit->setReadOnly( !enabled );
255
256 if ( mLineEdit )
257 {
258 mLineEdit->setReadOnly( !enabled );
259 mLineEdit->setFrame( enabled );
260 }
261}
262
264{
265 return mInvalidJSON;
266}
267
268void QgsTextEditWrapper::textChanged( const QString & )
269{
270 if ( mLineEdit )
271 {
272 //restore placeholder text, which may have been removed by showIndeterminateState()
273 mLineEdit->setPlaceholderText( mPlaceholderText );
274 }
275}
276
277void QgsTextEditWrapper::setWidgetValue( const QVariant &val )
278{
279 QString v;
280 if ( QgsVariantUtils::isNull( val ) )
281 {
282 if ( !( field().type() == QMetaType::Type::Int || field().type() == QMetaType::Type::Double || field().type() == QMetaType::Type::LongLong || field().type() == QMetaType::Type::QDate ) )
284 }
285 else if ( field().type() == QMetaType::Type::QVariantMap )
286 {
287 // this has to be overridden for json which has only values (i.e. no objects or arrays), as qgsfield.cpp displayString()
288 // uses QJsonDocument which doesn't recognise this as valid JSON although it technically is
289 if ( field().displayString( val ).isEmpty() )
290 {
291 if ( val.userType() == QMetaType::Type::QString && val.toString() != QLatin1String( "\"\"" ) )
292 {
293 v = val.toString().append( "\"" ).insert( 0, "\"" );
294 }
295 else
296 {
297 v = val.toString();
298 }
299 }
300 else
301 {
302 v = field().displayString( val );
303 }
304 }
305 else if ( val.userType() == QMetaType::Type::Double && std::isnan( val.toDouble() ) )
306 {
308 }
309 else
310 {
311 v = field().displayString( val );
312 }
313 // For numbers, remove the group separator that might cause validation errors
314 // when the user is editing the field value.
315 // We are checking for editable layer because in the form field context we do not
316 // want to strip the separator unless the layer is editable.
317 // Also check that we have something like a number in the value to avoid
318 // stripping out dots from nextval when we have a schema: see https://github.com/qgis/QGIS/issues/28021
319 // "Wrong sequence detection with Postgres"
320 bool canConvertToDouble;
321 QLocale().toDouble( v, &canConvertToDouble );
322 if ( canConvertToDouble && layer() && layer()->isEditable() && ! QLocale().groupSeparator().isNull() && field().isNumeric() )
323 {
324 v = v.remove( QLocale().groupSeparator() );
325 }
326
327 const QVariant currentValue = value( );
328 // Note: comparing QVariants leads to funny (and wrong) results:
329 // QVariant(0.0) == QVariant(QVariant.Double) -> True
330 const bool changed { val != currentValue || QgsVariantUtils::isNull( val ) != QgsVariantUtils::isNull( currentValue ) };
331
332 if ( changed )
333 {
334 if ( mTextEdit )
335 {
336 if ( config( QStringLiteral( "UseHtml" ) ).toBool() )
337 {
338 mTextEdit->setHtml( v );
339 if ( mTextBrowser )
340 {
341 mTextBrowser->setTextInteractionFlags( Qt::LinksAccessibleByMouse );
342 mTextBrowser->setOpenExternalLinks( true );
343 }
344 }
345 else
346 {
347 mTextEdit->setPlainText( v );
348 }
349 }
350 else if ( mPlainTextEdit )
351 {
352 mPlainTextEdit->setPlainText( v );
353 }
354 else if ( mLineEdit )
355 {
356 mLineEdit->setText( v );
357 }
358 }
359}
360
361void QgsTextEditWrapper::setHint( const QString &hintText )
362{
363 if ( hintText.isNull() )
364 mPlaceholderText = mPlaceholderTextBackup;
365 else
366 {
367 mPlaceholderTextBackup = mPlaceholderText;
368 mPlaceholderText = hintText;
369 }
370
371 if ( mLineEdit )
372 mLineEdit->setPlaceholderText( mPlaceholderText );
373}
static QString nullRepresentation()
Returns the string used to represent the value NULL throughout QGIS.
void displayWarning(const QString &message)
Displays a warning message in the form message bar.
Manages an editor widget Widget and wrapper share the same parent.
Q_DECL_DEPRECATED void valueChanged(const QVariant &value)
Emit this signal, whenever the value changed.
void setFormFeature(const QgsFeature &feature)
Set the feature currently being edited to feature.
int fieldIdx() const
Access the field index.
QVariant defaultValue() const
Access the default value of the field.
void valuesChanged(const QVariant &value, const QVariantList &additionalFieldValues=QVariantList())
Emit this signal, whenever the value changed.
void emitValueChanged()
Will call the value() method to determine the emitted value.
QgsField field() const
Access the field.
virtual void setValue(const QVariant &value)
Is called when the value of the widget needs to be changed.
The feature class encapsulates a single feature including its unique ID, geometry and a list of field...
Definition qgsfeature.h:58
Q_INVOKABLE QVariant attribute(const QString &name) const
Lookup attribute value by attribute name.
QString displayString(const QVariant &v) const
Formats string for display.
Definition qgsfield.cpp:317
QLineEdit subclass with built in support for clearing the widget's value and handling custom null val...
void setNullValue(const QString &nullValue)
Sets the string representation for null values in the widget.
static QVariant parseJson(const std::string &jsonString)
Converts JSON jsonString to a QVariant, in case of parsing error an invalid QVariant is returned and ...
void initWidget(QWidget *editor) override
This method should initialize the editor widget with runtime data.
QWidget * createWidget(QWidget *parent) override
This method should create a new widget with the provided parent.
void showIndeterminateState() override
Sets the widget to display in an indeterminate "mixed value" state.
void setHint(const QString &hintText) override
Add a hint text on the widget.
QgsTextEditWrapper(QgsVectorLayer *layer, int fieldIdx, QWidget *editor=nullptr, QWidget *parent=nullptr)
Constructor for QgsTextEditWrapper.
void setFeature(const QgsFeature &feature) override
bool isInvalidJSON()
Returns whether the text edit widget contains Invalid JSON.
void setEnabled(bool enabled) override
bool valid() const override
Returns true if the widget has been properly initialized.
QVariant value() const override
Will be used to access the widget's value.
static bool isNull(const QVariant &variant, bool silenceNullWarnings=false)
Returns true if the specified variant should be considered a NULL value.
static QVariant createNullVariant(QMetaType::Type metaType)
Helper method to properly create a null QVariant from a metaType Returns the created QVariant.
Represents a vector layer which manages a vector based data sets.
QgsVectorLayer * layer() const
Returns the vector layer associated with the widget.
QVariantMap config() const
Returns the whole config.
#define Q_NOWARN_DEPRECATED_POP
Definition qgis.h:6535
#define Q_NOWARN_DEPRECATED_PUSH
Definition qgis.h:6534