Reputation: 752
I want to have an only left border around my text in QTextDocument
I think the required css for this will be
<div style='
border-left: 6px solid red;
background-color: lightgrey;
'> Hello World </div>
but lets say I have this qt code
#include <QApplication>
#include <QWidget>
#include <QHBoxLayout>
#include <QTextEdit>
int main(int argc, char *argv[]) {
QApplication a(argc, argv);
QWidget *widget = new QWidget();
auto l = new QHBoxLayout(widget);
widget->setLayout(l);
QTextEdit *e = new QTextEdit(widget), *t = new QTextEdit(widget);
l->addWidget(e);
l->addWidget(t);
QObject::connect(e, &QTextEdit::textChanged, [=]() {
t->setHtml(e->toPlainText());
});
widget->show();
}
now if enter the html I got this output
but the correct and required output should be -
I want the above output, is there something I am missing?
Upvotes: 0
Views: 791
Reputation: 2083
For example,
.h
#ifndef LEFTBORDERTEXTEDIT_H
#define LEFTBORDERTEXTEDIT_H
#include <QTextEdit>
class LeftBorderTextEdit : public QTextEdit
{
Q_OBJECT
public:
LeftBorderTextEdit();
void paintEvent(QPaintEvent* e);
};
#endif // LEFTBORDERTEXTEDIT_H
.cpp
#include "LeftBorderTextEdit.h"
#include "qpainter.h"
#include <QTextBlock>
#include <QAbstractTextDocumentLayout>
LeftBorderTextEdit::LeftBorderTextEdit()
{
}
void LeftBorderTextEdit::paintEvent(QPaintEvent* e)
{
QPainter p = QPainter(viewport());
QPen pen = p.pen();
QBrush brush = p.brush();
pen.setBrush(QBrush(Qt::red, Qt::SolidPattern));
brush.setColor(Qt::red);
brush.setStyle(Qt::SolidPattern);
p.setPen(pen);
p.setBrush(brush);
int bc = document()->blockCount();
for (int i = 0; i < bc; i++)
{
qDebug() << i;
QTextBlock block = document()->findBlockByNumber(i);
QRectF bf = document()->documentLayout()->blockBoundingRect(block);
bf = QRectF(bf.left() - 5, bf.top(), 5, bf.height());
p.drawRect(bf);
}
p.end();
QTextEdit::paintEvent(e);
}
main.cpp
#include "MainWindow.h"
#include <QApplication>
#include "LeftBorderTextEdit.h"
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
LeftBorderTextEdit t;
w.setCentralWidget(&t);
w.show();
return a.exec();
}
Upvotes: 1
Reputation: 4869
Unfortunately Qt rich text in QTextDocument
doesn't support borders on anything except tables. And even then it is all borders at once, not individual sides. https://doc.qt.io/qt-5/richtext-html-subset.html#css-properties
UPDATE: Well this reminds me of writing HTML for MSIE back in 1996, but hey there's (almost) always a way... (the only CSS in here is actually optional, the "required output" image doesn't have padding :).
<!-- with width=100% the table extends all the way to the right margin -->
<table cellspacing=0 width='100%'>
<tr>
<td width=6 bgcolor='red'/>
<td bgcolor='lightgrey'
style='padding: 0 4px;'
>Hello World</td>
</tr>
</table>
Upvotes: 1