Qt QTextBrowser How to capture text and change its cursor - c++

I have QTextBrowser with delegate class ,
in the QTextBrowser i set html text with links , but in this html i have text that looks like
link with css like this:
"<span style=\" font-size:8pt; text-decoration: underline; color:#ffffff;\">dummy_link</span>"
i like to change the cursor type to point when the mouse over it . and then trigger Qt function .
the problem is that when i try to implement in the QTextBrowser with delegate class
the mouseMoveEvent(QMouseEvent *e) like this : all other links ( tags )loss there pointer cursors here is when i do :
void TextBrowserDelegate::mouseMoveEvent(QMouseEvent *e)
{
QCursor newCursor = cursor();
Qt::CursorShape CurrCursor = newCursor.shape();
QTextCursor tc = cursorForPosition( e->pos() );
tc.select( QTextCursor::WordUnderCursor );
QString sharStr = tc.selectedText();
if(sharStr == "dummy_link")
{
Qt::CursorShape newCursor = Qt::PointingHandCursor;//Qt::ArrowCursor;
setCursor(newCursor);
}
e->accept();
}
what im doing wrong here ?

With the code you've provided, it looks like only a link with the text "dummy_link" will get the cursor that you are choosing. The QTextBrowser class should automatically change the cursor if you set the proper flags.
QTextBrowser::setOpenLinks(true);
If your TextBrowserDelegate inherits from QTextBrowser you can use the following code in your constructor:
TextBrowserDelegate::TextBrowserDelegate(QWidget *parent){
this->setOpenExternalLinks(true);
this->setOpenLinks(true);
connect(this,SIGNAL(anchorClicked(QUrl)),this,SLOT(onClickedLink(QUrl)));
}
void TextBrowserDelegate::onClickedLink(QUrl url){
//do something with url
}

Related

Qt6: "Unable to read Memory" when pointing to a QLineEdit from a QFormLayout

I want to get the text from a QLineEdit, which is in a QFormLayout, to save it to a File. The saving works fine, but I am not able to get the text form the QLineEdit and when I look at it from the Debugger it says "Unable to read Memory". I canĀ“t figure out how to correctly point to the QLineEdit, so that I can get the text.
With this code I want to get the text:
QJsonArray Kegelbuch::saveSettings() {
QFormLayout* formLayout = (QFormLayout*)ui.einstellungenTab->layout();
QJsonArray data;
QLineEdit* settingsEdit;
for (int i = 0; i < formLayout->rowCount(); i++) {
settingsEdit = (QLineEdit*)formLayout->itemAt(i, QFormLayout::ItemRole::FieldRole);
}
return data;
}
How the window looks:
Replace
settingsEdit = (QLineEdit*)formLayout->itemAt(i, QFormLayout::ItemRole::FieldRole);
with
settingsEdit = (QLineEdit*)(formLayout->itemAt(i, FormLayout::ItemRole::FieldRole)->widget());
Background: itemAt() returns a QLayoutItem*, so you need to call QWidget *QLayoutItem::widget() to get the widget.

How to return QTextEdit RichText as plain text?

I have a QTextEdit whose textFormat is Qt::RichText so it is possible to format the text with HTML tags. On this QTextEdit I have a QPopupMenu thats filled with QActions. One of these actions is a simple copy that connects into SLOT( onClipboardCopy() ).
QTextEdit's copy() is defined as "Copies any selected text (from selection 0) to the clipboard."
If there is something selected this function is perfect. However, I'd like to copy ALL of the TextEdit's content when nothing is selected.
Here's the slot:
void WidgetName::onClipboardCopy()
{
if ( TextEdit->hasSelectedText() )
{
TextEdit->copy();
}
else
{
QClipboard * xClipboard = QApplication::clipboard();
xClipboard->setText( TextEdit->text() );
}
}
The problem is in else TextEdit->text() returns the text with all of it's HTML tags. Is there an easy way to discard them?
Okay, I realized that I could select the text before copying. I get the desired effect by changing the code to:
void WidgetName::onClipboardCopy()
{
if ( TextEdit->hasSelectedText() )
{
TextEdit->copy();
}
else
{
TextEdit->selectAll();
TextEdit->copy();
TextEdit->removeSelection();
//QClipboard * xClipboard = QApplication::clipboard();
//xClipboard->setText( TextEdit->text() );
}
}

QT5 C++, Is there a way I can get the current text of a widget within a qlist container

I need to retrieve the text in the order in which they appear on the user form. I am trying as below:
QString line = "QLineEdit";
QString combo = "QComboBox";
QList<QWidget *> childWidgets = ui->frame_3->findChildren<QWidget *>();
QStringList data;
for(auto widget : childWidgets){
if(widget->metaObject()->className() == line || widget->metaObject()->className() == combo){
data.append(widget->text()); //append the text of the lineEdits and ComboBoxes to data
}
}
I get the following compile error from the above code:
"no member named 'text' in QWidget
Since you pointed out the QWidget base class does not have a text member function you will need to access the QComboBox and QLineEdit directly to get the current text.
QList<QWidget *> childWidgets = ui->frame_3->findChildren<QWidget *>();
QStringList data;
for(auto widget : childWidgets){
auto combo = dynamic_cast<QComboBox*>(widget);
if (combo) {
data << combo->currentText(); // currentText() returns the text from the combobox
}
else {
auto lineEdit = dynamic_cast<QLineEdit*>(widget);
if (lineEdit) {
data << lineEdit->text(); // A line edit has a text() member.
}
}
}
This code does not handle ordering. I believe the order is in the same order as added to the parent.

Why QTextDocument background color changes only once?

I am using TextEditor from the example provided with Qt (https://doc.qt.io/qt-5/qtquickcontrols1-texteditor-example.html). Here is the complete code https://code.qt.io/cgit/qt/qtquickcontrols.git/tree/examples/quickcontrols/controls/texteditor?h=5.15
I have created a custom method void DocumentHandler::setBackgroundColor(const QColor &color) to change the background color of the overall HTML document.
My problem is whenever I call a method to change the background color of QTextDocument using setDefaultStyleSheet, it is executed only once. ie, my document background changes only once. For the next calls, I can see the qDebug printing correctly, but the setDefaultStyleSheet doesn't work. However, everything works perfectly with normal text, only not with m_doc->toHtml().
How do I fix this?
If I change m_doc->setHtml("some random text"), it works as required
...
QColor DocumentHandler::backgroundColor() const
{
return m_backgroundColor;
}
void DocumentHandler::setBackgroundColor(const QColor &color)
{
m_backgroundColor = color.name(); // QColor variable
m_doc->setDefaultStyleSheet("body{background-color: '"+ color.name() +"'}"); // m_doc is QTextDocument *
m_doc->setHtml(m_doc->toHtml());
qDebug() << "BACKGROUND COLOR CHANGED" << color.name() ;
emit backgroundColorChanged();
}
In the QML, I have called it like this
...
DocumentHandlerModel {
id: document
target: textArea
cursorPosition: textArea.cursorPosition
selectionStart: textArea.selectionStart
selectionEnd: textArea.selectionEnd
backgroundColor: colorDialog2.color
onFontFamilyChanged: {
var index = Qt.fontFamilies().indexOf(document.fontFamily)
if (index === -1) {
fontFamilyComboBox.currentIndex = 0
fontFamilyComboBox.special = true
} else {
fontFamilyComboBox.currentIndex = index
fontFamilyComboBox.special = false
}
}
onError: {
errorDialog.text = message
errorDialog.visible = true
}
}
Cause
The documentation of QTextDocument::setDefaultStyleSheet says:
Note: Changing the default style sheet does not have any effect to the existing content of the document.
You try to overcome this by calling setHtml after setDefaultStyleSheet like that:
m_doc->setHtml(m_doc->toHtml());
However, this does not produce the desired result, because setDefaultStyleSheet actually embeds the background color in the HTML through the bgcolor CSS property.
To test this, add
m_doc->setHtml("<html><body><p>Test</p></body></html>");
qDebug() << m_doc->toHtml();
after
m_doc->setHtml(m_doc->toHtml());
The HTML content of m_doc from <html><body><p>Test</p></body></html>, when tested with #FF00FF, becames:
"<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n<html><head><meta name=\"qrichtext\" content=\"1\" /><style type=\"text/css\">\np, li { white-space: pre-wrap; }\n</style></head><body style=\" font-family:'MS Shell Dlg 2'; font-size:8.25pt; font-weight:400; font-style:normal;\" bgcolor=\"#ff00ff\">\n<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">Test</p></body></html>"
Note: Please, notice that assignment: bgcolor=\"#ff00ff\.
So, by writing m_doc->setHtml(m_doc->toHtml()); you effectively return the old color. That is why the color changes only the first time.
By the way, the widget now changes its color, but has lost its content.
Solution
It is hard to find an elegant solution, because in this case markup and styles are not kept separate, as in real HTML and CSS, but the style is embedded by Qt in the markup. The one thing which comes to my mind, is to parse the content of m_doc manually.
Note: Such a solution would be extremely fragile and I advise strongly against it. Maybe instead of using a stylesheet, change the background color by setting up the palette of the widget, which renders the content of the QTextDocument on the screen.
Note: In any case this does not seem like the intended behavior, at least it does not match the description in the documentation, so I would have reported it as a bug to Qt, if I were you.
Example
Here is an example I wrote for you in order to demonstrate the proposed solution:
void DocumentHandler::setBackgroundColor(const QColor &color)
{
const QString &bgcolor("bgcolor=\"");
QString html(m_doc->toHtml());
int n = html.indexOf(bgcolor, html.indexOf("<body"));
int k = n + bgcolor.length();
m_doc->setDefaultStyleSheet("body { background-color: '" + color.name() + "' }");
if (n >= 0)
html.replace(n + bgcolor.length(), html.mid(k, html.indexOf("\"", n + bgcolor.length()) - k).length(), color.name());
m_doc->setHtml(html);
m_backgroundColor = color.name(); // QColor variable
emit backgroundColorChanged();
}

QFileDialog: How to select multiple files with touch-screen input?

In our application that uses Qt 4 and supports touch input, we use the QFileDialog with the options QFileDialog::DontUseNativeDialog and QFileDialog::ExistingFiles.
The first is needed because we set our own stylesheet and that does not work with the native dialog. The second is for needed for selecting multiple files, which is what we want to do.
The problem ist that one can not select multiple files with touch input in the QFileDialog, because we have no "shift" or "ctrl"-key available. In Windows the problem is solved by adding checkboxes to the items. QFileDialog has no checkboxes.
I tried to manipulate the QFileDialog to make it displays check boxes for the items, but I failed.
I tried to exchanged the QFileSystemModel that is used by the underlying QTreeView and QListView, but this breaks the signal-slot connections between the model and the dialog. I could not find a way to restore them because they are burried deep in the private intestants of the dialog.
At this moment the only solution I can imagine is writing a whole new dialog, but I would like to avoid the effort.
So is there a way to add checkboxes to the QFileDialog model views ?
Do you have another idea how selecting multiple files could be made possible?
Is the problem fixed in Qt 5? We want to update anyway.
Thank you for your Help.
As I failed to add checkboxes to the item views, I implemented a "hacky" work-around. It adds an extra checkable button to the dialog that acts as a "ctrl"-key. When the button is checked, multiple files can be selected. The solution is a little bit ugly, because it relies on knowing the internals of the dialog, but it does the job.
So here is the code for the header ...
// file touchfiledialog.h
/*
Event filter that is used to add a shift modifier to left mouse button events.
This is used as a helper class for the TouchFileDialog
*/
class EventFilterCtrlModifier : public QObject
{
Q_OBJECT;
bool addCtrlModifier;
public:
EventFilterCtrlModifier( QObject* parent);
void setAddCtrlModifier(bool b);
protected:
virtual bool eventFilter( QObject* watched, QEvent* e);
};
/*
TouchDialog adds the possibility to select multiple files with touch input to the QFileDialog.
This is done by adding an extra button which can be used as control key replacement.
*/
class QTOOLS_API TouchFileDialog : public QFileDialog
{
Q_OBJECT
EventFilterCtrlModifier* listViewEventFilter;
EventFilterCtrlModifier* treeViewEventFilter;
bool initialized;
public:
TouchFileDialog( QWidget* parent);
protected:
virtual void showEvent( QShowEvent* e);
private slots:
void activateCtrlModifier(bool b);
private:
void initObjectsForMultipleFileSelection();
};
with the implementation ...
// file touchfiledialog.cpp
#include "touchfiledialog.h"
EventFilterCtrlModifier::EventFilterCtrlModifier(QObject* parent)
: QObject(parent)
, addCtrlModifier(false)
{
}
void EventFilterCtrlModifier::setAddCtrlModifier(bool b)
{
addCtrlModifier = b;
}
bool EventFilterCtrlModifier::eventFilter(QObject* watched, QEvent* e)
{
QEvent::Type type = e->type();
if( type == QEvent::MouseButtonPress || type == QEvent::MouseButtonRelease)
{
if( addCtrlModifier)
{
QMouseEvent* mouseEvent = static_cast<QMouseEvent*>(e);
// Create and post a new event with ctrl modifier if the event does not already have one.
if( !mouseEvent->modifiers().testFlag(Qt::ControlModifier))
{
QMouseEvent* newEventWithModifier = new QMouseEvent(
type,
mouseEvent->pos(),
mouseEvent->globalPos(),
mouseEvent->button(),
mouseEvent->buttons(),
mouseEvent->modifiers() | Qt::ControlModifier
);
QCoreApplication::postEvent(watched, newEventWithModifier);
return true; // absorb the original event
}
}
}
return false;
}
//#######################################################################################
TouchFileDialog::TouchFileDialog(QWidget* parent)
: QFileDialog(parent)
, listViewEventFilter(NULL)
, treeViewEventFilter(NULL)
, initialized(false)
{
}
void TouchFileDialog::showEvent(QShowEvent* e)
{
// install objects that are needed for multiple file selection if needed
if( !initialized)
{
if( fileMode() == QFileDialog::ExistingFiles)
{
initObjectsForMultipleFileSelection();
}
initialized = true;
}
QFileDialog::showEvent(e);
}
void TouchFileDialog::initObjectsForMultipleFileSelection()
{
// install event filter to item views that are used to add ctrl modifiers to mouse events
listViewEventFilter = new EventFilterCtrlModifier(this);
QListView* listView = findChild<QListView*>();
listView->viewport()->installEventFilter(listViewEventFilter);
treeViewEventFilter = new EventFilterCtrlModifier(this);
QTreeView* treeView = findChild<QTreeView*>();
treeView->viewport()->installEventFilter(treeViewEventFilter);
QGridLayout* dialogLayout = static_cast<QGridLayout*>(layout()); // Ugly because it makes assumptions about the internals of the QFileDialog
QPushButton* pushButtonSelectMultiple = new QPushButton(this);
pushButtonSelectMultiple->setText(tr("Select multiple"));
pushButtonSelectMultiple->setCheckable(true);
connect( pushButtonSelectMultiple, SIGNAL(toggled(bool)), this, SLOT(activateCtrlModifier(bool)));
dialogLayout->addWidget(pushButtonSelectMultiple, 2, 0);
}
void ZFFileDialog::activateCtrlModifier(bool b)
{
listViewEventFilter->setAddCtrlModifier(b);
treeViewEventFilter->setAddCtrlModifier(b);
}
The TouchFileDialog installs an event filter to the item views that will add a ControlModifier to the mouse events of the views when the corresponging button in the dialog is checked.
Feel free to post other solutions, because this is somewhat improvised.