Trying to set the colour for hyperlinks in QTextBrowser
-
I added the following at the start of the text browser content:
<head><style>a:link {color: #e0ffff;}</style></head> <body bgcolor=#1e1e1e>
using insertHTML().
I expected it to change the colour of hyperlinks, but it doesn't seem to do so.
What am I doing wrong please?
-
@Perdrix
My recommendation: first determine how links are being output as HTML inQTextBrowser
, e.g. are they<a>
elements, does it maybe insert a<span>
? Then get whatever working directly on the HTML link. Finally try moving that to the<head><style>a:link ...
global rule.Remember
QTextBrowser
is by no means full HTML, only certain things work. -
@Perdrix QTextBrowser inherits QTextEdit
#include <QApplication> #include <QTextEdit> #include <QTextDocument> int main(int argc, char *argv[]) { QApplication a(argc, argv); // Create a QTextEdit widget QTextEdit textEdit; // Set HTML content with color and style QString htmlContent = "<span style='color:red; font-weight:bold;'>Hello, <i>world!</i></span>"; textEdit.setHtml(htmlContent); // Show the QTextEdit widget textEdit.show(); return a.exec(); }
-
@Perdrix Try it out
#include <QApplication> #include <QTextEdit> #include <QTextDocument> #include <iostream> int main(int argc, char *argv[]) { QApplication app(argc, argv); // Create a QTextEdit widget QTextEdit textEdit; QString htmlContent = QString( "<head></head><body><p>Visit the <a href=\"https://www.example.com\"><span style=\"color: blue;\">Example Website</span></a>.</p> </body>" ); // Set HTML content with color and style //QString htmlContent = "<span style='color:red; font-weight:bold;'>Hello, <i>world!</i></span>"; textEdit.setHtml(htmlContent); // Show the QTextEdit widget textEdit.show(); return app.exec(); }
-
@Perdrix Your CSS works for me on unvisited links (a:link selector).
#include <QApplication> #include <QTextBrowser> #include <QTextDocument> #include <iostream> int main(int argc, char *argv[]) { QApplication app(argc, argv); QTextBrowser textBrowser; QString htmlContent = QString( R"( <head> <style> a:link {color: red; } </style> </head> <body> <p><a href="#link">Link</a></p> </body> )" ); textBrowser.setHtml(htmlContent); textBrowser.show(); return app.exec(); }
-
@Perdrix Sorry to come later on this. But there is an interesting note about this in documentation of QPalette:
Note that we do not use the Link and LinkVisited roles when rendering rich text in Qt, and that we recommend that you use CSS and the QTextDocument::setDefaultStyleSheet() function to alter the appearance of links. For example:
QTextBrowser browser; QColor linkColor(Qt::red); QString sheet = QString::fromLatin1("a { text-decoration: underline; color: %1 }").arg(linkColor.name()); browser.document()->setDefaultStyleSheet(sheet);