diff --git a/src/plugins/texteditor/basetexteditor.cpp b/src/plugins/texteditor/basetexteditor.cpp
index f1ac66d43bf9f4e02655275c31ab85dc6f2453ca..9d317ddcd38a4bb80564847389595433ee05494a 100644
--- a/src/plugins/texteditor/basetexteditor.cpp
+++ b/src/plugins/texteditor/basetexteditor.cpp
@@ -1763,6 +1763,8 @@ void BaseTextEditor::paintEvent(QPaintEvent *e)
 
     QPointF offset(contentOffset());
 
+    bool hasMainSelection = textCursor().hasSelection();
+
     QRect er = e->rect();
     QRect viewportRect = viewport()->rect();
 
@@ -1859,7 +1861,7 @@ void BaseTextEditor::paintEvent(QPaintEvent *e)
             int bllen = block.length();
 
             QVector<QTextLayout::FormatRange> selections;
-            QVector<QTextLayout::FormatRange> selectionsWithText;
+            QVector<QTextLayout::FormatRange> prioritySelections;
 
             for (int i = 0; i < context.selections.size(); ++i) {
                 const QAbstractTextDocumentLayout::Selection &range = context.selections.at(i);
@@ -1875,8 +1877,11 @@ void BaseTextEditor::paintEvent(QPaintEvent *e)
                         o.start = qMin(blockSelection->firstColumn, bllen-1);
                         o.length = qMin(blockSelection->lastColumn, bllen-1) - o.start;
                     }
-                    if (o.format.foreground().style() != Qt::NoBrush)
-                        selectionsWithText.append(o);
+                    if ((hasMainSelection && i == context.selections.size()-1)
+                        || (o.format.foreground().style() == Qt::NoBrush
+                        && o.format.underlineStyle() != QTextCharFormat::NoUnderline
+                        && o.format.background() == Qt::NoBrush))
+                        prioritySelections.append(o);
                     else
                         selections.append(o);
                 } else if (!range.cursor.hasSelection() && range.format.hasProperty(QTextFormat::FullWidthSelection)
@@ -1890,14 +1895,11 @@ void BaseTextEditor::paintEvent(QPaintEvent *e)
                     if (o.start + o.length == bllen - 1)
                         ++o.length; // include newline
                     o.format = range.format;
-                    if (o.format.foreground().style() != Qt::NoBrush)
-                        selectionsWithText.append(o);
-                    else
-                        selections.append(o);
+                    selections.append(o);
                 }
             }
             d->highlightSearchResults(block, &selections);
-            selections += selectionsWithText;
+            selections += prioritySelections;
 
             bool drawCursor = ((editable || true) // we want the cursor in read-only mode
                                && context.cursorPosition >= blpos