How to add css stylesheet to a QWebEngineView? - c++

I'm trying to follow this Qt example for adding CSS stylesheet to a QWebEngineView, however, I'm getting this error:
use of undefined type 'QWebEngineScriptCollection'
at the line ui.webEngineView->page()->scripts().insert(script);
What I'm missing? Testing using qt 6.4 Visual Studio 2022, the project can be reproduced by simply adding a QWebEngineView to the ui, and
#include "stdafx.h"
#include "MainWindow.h"
#include <QWebEngineScript>
void MainWindow::insertStyleSheet(const QString& name, const QString& source, bool immediately)
{
QWebEngineScript script;
QString s = QString::fromLatin1("(function() {"\
" css = document.createElement('style');"\
" css.type = 'text/css';"\
" css.id = '%1';"\
" document.head.appendChild(css);"\
" css.innerText = '%2';"\
"})()").arg(name).arg(source.simplified());
if (immediately)
ui.webEngineView->page()->runJavaScript(s, QWebEngineScript::ApplicationWorld);
script.setName(name);
script.setSourceCode(s);
script.setInjectionPoint(QWebEngineScript::DocumentReady);
script.setRunsOnSubFrames(true);
script.setWorldId(QWebEngineScript::ApplicationWorld);
ui.webEngineView->page()->scripts().insert(script);
}
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
{
ui.setupUi(this);
}

Fixed it. The correct include is:
#include <QtWebEngineCore/qwebenginescriptcollection.h>

Related

QPolarChart and QLineSeries error when plotting line over 0/360 degree

I am trying to create a polar plot with a line series. Sometimes the line will go from ie. 330° to 30°. However the plotted line has an additional point at (0,0).
Is there a way to change that behavior or might that be a bug due to the discontinuity of 360° being equivalent of 0°.
I expect this to be a common scenario, but i did not found anything about this problem online. (However all the examples avoid this 360°/0° transition or start at 0° and end at 360°.)
This is the output i get from the plot:
This minimal example was generated with the following code:
#include "MainWindow.hpp"
#include "./ui_MainWindow.h"
#include <QChart>
#include <QPolarChart>
#include <QLineSeries>
#include <QValueAxis>
#include <QChartView>
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
auto series = new QtCharts::QLineSeries();
series->append(330,60);
//series->append(360,60); (with both lines enabled the problem still occurs)
//series->append(0,60);
series->append(30,60);
series->append(60,60);
series->append(90,60);
auto chart = new QtCharts::QPolarChart();
chart->addSeries(series);
auto angularAxis = new QtCharts::QValueAxis();
angularAxis->setTickCount(9);
angularAxis->setMin(0);
angularAxis->setMax(360);
angularAxis->setLabelFormat("%.1f");
chart->addAxis(angularAxis, QtCharts::QPolarChart::PolarOrientationAngular);
series->attachAxis(angularAxis);
auto *radialAxis = new QtCharts::QValueAxis();
radialAxis->setTickCount(9);
radialAxis->setMin(0);
radialAxis->setMax(90);
radialAxis->setLabelFormat("%.1f");
chart->addAxis(radialAxis, QtCharts::QPolarChart::PolarOrientationRadial);
series->attachAxis(radialAxis);
auto view = new QtCharts::QChartView(chart);
centralWidget()->layout()->addWidget(view);
}
MainWindow::~MainWindow()
{
delete ui;
}

Filtering files of specific folder using QFileSystemModel and QSortFilterProxyModel subclass

I am trying to filter files of QFileSystemModel using QSortFilterProxyModel. The problem is, I want to only show the contents of a specific folder while filtering. Normally, if I wanted to only show the contents of a specific folder using QFileSystemModel, I would do something like this:
view = new QTreeView(this);
fSystemModel = new QFileSystemModel(this);
view->setModel(fSystemModel);
fSystemModel->setRootPath("C:/Qt");
QModelIndex idx = fSystemModel->index("C:/Qt");
view->setRootIndex(idx);
But when I use the QSortFilterProxyModel, the index has to be the QSortFilterProxyModel's. Since I could not find much information in Qt Documentation regarding this issue, I looked around and found this thread. Using this as a base, I created the following:
MainWindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDebug>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
layout = new QVBoxLayout();
ui->centralWidget->setLayout(layout);
view = new QTreeView(this);
fSystemModel = new QFileSystemModel(this);
filter = new FilterModel();
filter->setSourceModel(fSystemModel);
layout->addWidget(view);
view->setModel(filter);
fSystemModel->setRootPath("C:/Qt");
QModelIndex idx = fSystemModel->index("C:/Qt");
QModelIndex filterIdx = filter->mapFromSource(idx);
qDebug() << filterIdx.isValid();
view->setRootIndex(filterIdx);
}
FilterModel.cpp (QSortFilterProxyModel subclass)
#include "filtermodel.h"
bool FilterModel::filterAcceptsRow(int source_row, const QModelIndex &source_parent) const
{
QModelIndex zIndex = sourceModel()->index(source_row, 0, source_parent);
QFileSystemModel* fileModel = qobject_cast<QFileSystemModel*>(sourceModel());
return fileModel->fileName(zIndex).contains("C"); //This line will have custom
//filtering behaviour in the future,
//instead of the name searching one.
}
However, when I run the program, it does not use the specified root index. Moreover, when I use qDebug() to see if the filterIdx is valid, it prints false. What am I doing wrong?
Try to see the result of the next line
qDebug() << idx << " " << fSystemModel->fileName(idx) << " " << filterIdx.isValid();
You can notice that fSystemModel->fileName(idx) is "Qt" (not full path "C:/Qt"). So it doesn't contain "C" from your filter (FilterModel::filterAcceptsRow).

How to clear a label in qt creator

this is the first time i write in this site, I'm trying approach me at Qt-creator but I've a problem:
I want to delete the text of the label when the user click a button, i've tried some solution but without success
this is the code:
struct finestra{
float costo;
int altezza;
int larghezza;
QString text;
QString costoStr;
};
float Totale=0;
finestra vet[21];
int i=1;
//SOME CODE
Totale+=vet[i].costo;
vet[i].costoStr = QString::number(vet[i].costo);
vet[i].text = vet[i-1].text + "Finestra ad un anta bianca <br>" + "€" + vet[i].costoStr +"<br>";
ui->TotaleFinestre->setText(QString(vet[i].text));
i++;
I've tried with this function:
void preventivi::on_pushButton_clicked()
{
ui->TotaleFinestre->clear();
}
if someone know how to do please answer,
thanks to all and sorry for my bad english.
Maybe you should try
void preventivi::on_pushButton_clicked()
{
ui->TotaleFinestre->setText("");
}
As QLabel define the slot void QLabel::clear(), you can also just connect this slot with the clicked() signal that will be emitted after a click on your pushButton, using the QObject::connect method :
QObject::connect(pointer_to_your_pushButton, SIGNAL(clicked()), pointer_to_your_label, SLOT(clear()));
EDIT : Here is a small example
The UI is a QWidget that has a QLabel and a QPushButton. I did that with Qt Designer but it doesn't matter here.
#include "widget.h"
#include "ui_widget.h"
Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
ui->setupUi(this);
QObject::connect(ui->pushButton, SIGNAL(clicked()), ui->label, SLOT(clear()));
}
Widget::~Widget()
{
delete ui;
}
You can even do that using "Edit Signals/Slots" inside Qt Designer and make the signal/slot connection between your widgets. ( you won't need to manually call the previous QObject::connect, as it will be done automatically inside the Ui_Widget class, generated by the uic)
Or you can do all without Qt Designer, it's up to you.
Hope this helps.

Accessing the variables of a parent widget via a button

I'm trying to implement a default button. This button should access strings of the parent widget which is a dialog box which the button is found on. I pasted the relevant parts of the code below. What I want is to be able to place strings to their corresponding lineEdit's when default values is clicked. For example pulse_string goes to ui->pulse_freq and nr_pulsestring goes into ui->nr_pulses etc.
#include "settings.h"
#include "ui_settings.h"
#include <QLineEdit>
#include <QSlider>
#include <QSpinBox>
int pulse_freq = 25000;
int nr_pulses = 10;
int samp_freq = 150000;
int nr_samples = 2000;
int gain = 32;
int accumulate = 1;
int acq_start = 0;
Settings::Settings(QWidget *parent) :
QDialog(parent),
ui(new Ui::Settings)
{
QString pulse_string, nr_pulsestring, sampfreq_string, nr_samplestring, gain_string;
QString accumulate_string, acq_string;
}
Settings::~Settings()
{
delete ui;
}
void Settings::on_Default_Values_clicked()
{
ui->pulse_freq->setText("25000");
ui->nr_pulses->setText("10");
ui->samp_freq->setText("150000");
ui->nr_samples->setText("2000");
ui->gain->setText("32");
ui->accumulate->setText("1");
ui->acq_start->setText("0");
}
You can use something looking like follows:
ui->pulse_freq->setText(QString("%1").arg(pulse_freq));
Since it seems you are only using numbers it would be better using a spinbox to insert values, so you dont have to check if an input is a valid number, etc.

Alternative way to print Arabic text in qt

I'm trying to print an HTML web page that contains Arabic text in Qt. Everything prints fine, but the Arabic text doesn't print properly.
First I tried this:
#include "mainwindow.h"
#include "ui_mainwindow.
#include <QtPrintSupport/QPrinter>
#include <QString>
#include <QtPrintSupport/QPrintDialog>
#include <QTextDocument>
#include <QFile>
#include <QDir>
#include <QFileDialog>
#include <QTextCodec>
#include <QtWebKitWidgets/QWebPage>
#include <QtWebKitWidgets/QWebView>
#include <QtWebKitWidgets/QWebFrame>
QString htmlItem(QString Item)
{
QString r="";
r.append( "<td>"
"<p align=\"center\" style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-family:'Tahoma'; font-size:9pt; font-weight:600;\">");
r.append(Item);
r.append("</span></p></td>");
return r;
}
QString htmlRow(QString MFC,QString MFT,QString D,QString N)
{
QString ret ="" ;
ret.append("<tr>");
ret.append(htmlItem(MFC));
ret.append(htmlItem(MFT));
ret.append(htmlItem(D));
ret.append(htmlItem(N));
ret.append("</tr>");
return ret;
}
QString htmlTable(QString rows)
{
QString ret = "";
ret.append("<table border=\"1\" style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px;\" align=\"center\" width=\"90%\" cellspacing=\"0\" cellpadding=\"4\">"
"<tbody>");
ret.append(rows);
ret.append("</tbody></table>");
return ret ;
}
QString htmlClientName(QString name)
{
QString retu="<p align=\"center\" style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\""
"font-family:'Tahoma'; font-size:16pt; font-weight:600;\">";
retu.append(name);
retu.append("</span></p>");
return retu;
}
QString htmlClientPage(QString Table,QString Name)
{
QString r = "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">"
"<!-- saved from url=(0045)file:///C:/Users/MG/Desktop/Untitled%201.html "
"-->"
"<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\"><meta name=\"qrichtext\" content=\"1\"><title>QTextEdit Example</title><style "
"type=\"text/css\">"
"p, li { white-space: pre-wrap; }"
"</style></head><body style=\" font-family:'MS Shell Dlg 2'; font-size:8.25pt; font-weight:400; font-"
"style:normal;\"";
r.append(htmlClientName(Name));
r.append(htmlTable(Table));
r.append("</body></html>");
return r;
}
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_pushButton_clicked()
{
QString cD="";
cD.append(htmlRow("m","n","b","v"));
cD.append(htmlRow("hgfh","n","b","gggg"));
cD.append(htmlRow("m","vvvv","bbbbbbb","v"));
cD.append(htmlRow("m","ssssss","b","sssssssss"));
QString data = htmlClientPage(htmlTable(cD), "???? ???? ");
ui->textEdit->setText(data);
#if !defined(QT_NO_PRINTER) && !defined(QT_NO_PRINTDIALOG)
QPrinter printer(QPrinter::HighResolution);
QPrintDialog *dlg = new QPrintDialog(&printer, this);
if (ui->textEdit->textCursor().hasSelection())
dlg->addEnabledOption(QAbstractPrintDialog::PrintSelection);
dlg->setWindowTitle(tr("Print Document"));
if (dlg->exec() == QDialog::Accepted)
ui->textEdit->print(&printer);
delete dlg;
#endif
}
The output printed file was like this:
I searched for how to solve this problem and ended up with sum bugs in Qt when printing Arabic text. And I tried some other Qwidgets like QwebView and QwebPage and ended up with more problems.
Now I'm asking if there is an alternative way to use Qt printing like Windows API or something else to solve this problem.
I use
SDK : Qt 5.2.1 with Qt Creator 3.0.1
Operating System : Microsoft Windows 8
Edit: I need to mention that Qt prints Arabic text to PDF well.
Edit: I'm pretty sure that the problem is not the encoding. I searched for this problem and I found these bugs in Qt:
https://bugreports.qt-project.org/browse/QTBUG-4452?page=com.atlassian.jira.plugin.system.issuetabpanels:worklog-tabpanel
I think the problem is related to this one.
This:
QString str = QString::fromLocal8Bit(data.toLocal8Bit());
doesn't make sense to me. I am not sure if it will work, but try the following:
ui->textEdit->setText(htmlArabicPage);
and tell me what happens.
Also if you have this:
htmlClientPage(htmlTable(cD),"محمد جمال ");
in your source code, you should be very careful. If you want to create a Unicode literal in C++11 then you should do:
u8"محمد جمال "
where the text is encoded in UTF-8.
Otherwise, you should try if "محمد جمال " is being interpreted well. Try this:
#include <QString>
#include <QDebug>
int main()
{
qDebug() << QString::fromUtf8("محمد جمال ");
qDebug() << QString::fromLocal8Bit("محمد جمال ");
return 0;
}
The bug you posted is from the previous version of Qt and it has been closed.