Can't get QSettings to write my settings properly - c++

So I have the tutorial project Notepad. I am trying to use QSettings so that it saves the font,font size and other font related options in a file but it never loads them properly and when I check the config file, the values look quite weird.
void Notepad::saveSettings()
{
QSettings setting("MyTE","myte");
QFont font = this->font();
setting.beginGroup("MainWindow");
setting.setValue("text.font",font.toString());
setting.setValue("text.font.family",font.family());
setting.setValue("text.font.size",font.pointSize());
setting.setValue("text.font.bold",font.bold());
setting.setValue("text.font.italic",font.italic());
setting.endGroup();
qDebug() << "Saved";
}
void Notepad::loadSettings(){
QSettings setting ("MyTE","myte");
QFont font = setting.value("text.font",QString()).toString();
setting.beginGroup("MainWindow");
QString fontFamily = setting.value("text.font.family",QString()).toString();
int fontSize = setting.value("text.font.size",12).toInt();
setting.setValue("text.font.size",fontSize);
//bool fontIsBold = setting.value("text.font.bold",false).toBool();
//bool fontIsItalic = setting.value("text.font.italic",false).toBool();
setFont(font);
font.setPointSize(fontSize);
setting.endGroup();
qDebug() << "Loaded";
}
I uncommented the bold ones because they simply don't work.
I have 2 buttons that correspond to these 2 functions and I also call loadSettings() when the app first starts.
Here is the output in the config file, that never changes and just resets to these weird values.
[MainWindow]
text.font=",9,-1,5,50,0,0,0,0,0"
text.font.bold=false
text.font.family=
text.font.italic=false
text.font.size=9

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.

Why my C++ Qt UI got translated but not my QStrings in my program?

I needed to translate my english UI in french, so I did all the necessary with .ts and .qm files, load it in the QTranslator class, and install it to the QApplication:
//in the InterfaceWidget constructor:
QTranslator myappTranslator;
bool loaded = myappTranslator.load("myApp_" + QLocale::system().name());
qDebug() << "Is translation file loaded?" << loaded; // RETURNS TRUE
QApplication::installTranslator(&myappTranslator);
ui.setupUi(this);
ui.retranslateUi(this); //works, it translates the UI
Later, I create and attach to the InterfaceWidget another Widget (in a tab) called ConfigurationTabUI :
m_ConfigurationTabUI = new ConfigurationTabUI(ui.configTab);
The corresponding UI is also translated to french, correctly.
And here is my problem: in the ConfigurationTabUI's methods, it doesn't work when I try to translate a simple QString:
void ConfigurationTabUI::on_ValidButton_clicked(){
QString msg(ConfigurationTabUI::tr("message to translate"));
qDebug() << "translated string: " << msg; // NOT TRANSLATED
}
I really have no clue why...
Thanks for your help.
Note: I Use Qt5.2 and I double checked that the .ts file contains the right translated string.
Ok, I found the problem, it's just a dumb oversight:
QTranslator is created on the stack and not dynamically (on the heap), so the object is destroyed at the end of the method.
As a result, it translates the UI because the object is still there but later, when a slot is called, nothing get translated.
Here is my code:
//in the InterfaceWidget constructor:
QTranslator* myappTranslator = new QTranslator(QApplication::instance());
bool loaded = myappTranslator->load("myApp_" + QLocale::system().name());
qDebug() << "Is translation file loaded?" << loaded; // RETURNS TRUE
QApplication::installTranslator(myappTranslator);
ui.setupUi(this);
and in ConfigurationTabUI (which inherits from QWidget):
void ConfigurationTabUI::changeEvent(QEvent *e)
{
if (e->type() == QEvent::LanguageChange) {
ui.retranslateUi(this);
reset(); //my method to reload some data in UI
} else
QWidget::changeEvent(e);
}

Released app does not work as the original

I have a file with hundreds and hundreds of pictures (photographs) that I need to show in preview to some people. This preview should be a purchase order (rapidly, nothing "pro") and I would give them so that the people can put a cross in the case they want a picture and which size (as simple as that).
I tried to auto-generate the purchase order, there would be two per page (A4) on a PDF.
I use Qt/C++ and three objects :
QPdfWriter
QPainter
QImage
Here's the beginning of the pdf-generation class :
int order = 1;
qDebug() << "pdf creation";
QString logoName = QFileDialog::getOpenFileName(0, "Sélectionner le logo", QString(), "Images (*.png *.bmp *.jpg)");
QString fileName = QFileDialog::getSaveFileName(0, "Export PDF",
QString(), "*.pdf");
QString dir = QFileDialog::getExistingDirectory(0, "Sélectionner le dossier de photos");
QFont titleFont("Arial", 24);
titleFont.setUnderline(true);
QFont textFont("Times new roman", 12);
QDirIterator it(dir);
if (!fileName.isEmpty()) {
if (QFileInfo(fileName).suffix().isEmpty())
fileName.append(".pdf");
QPdfWriter writer(fileName);
QPainter painter(&writer);
painter.setRenderHint(QPainter::Antialiasing);
int height = painter.device()->height();
int semi = height/2;
int width = painter.device()->width();
int digits = 1;
qDebug() << "height : " << height << " width : " << width;
QImage logo(logoName);
QImage finalLogo = logo.scaled(3750, 1250, Qt::KeepAspectRatio);
while(it.hasNext()){
it.next();
digits = countDigits(order);
if(it.fileInfo().isFile()){
if(order%2!=0){
painter.drawImage(300,100,finalLogo);
QImage currentPreview(it.filePath());
QImage finalPreview = currentPreview.scaled(3250,4000, Qt::KeepAspectRatio);
painter.drawImage(650,1500,finalPreview);
The rest is just the drawing of the text/borders.
I tried it in debug : works fine
I compiled in release, put all the .dll in the file (including platform) and ran it without Qt : works fine
Then I put the files on a usb stick, I put it on the other computer that I use for the pictures, that computer does NOT have Qt.
I launched the .exe and the app showed exactly as on my dev-pc
But when I called the PDF creation I filled the FileDialogs with my data, it runs for around 30 secs (a lot of pictures in the file) and generates the PDF.
I opened it and ... not a single picture on the PDF.
All the lines and texts are in place without any problem, it generates the right amount of purchase order but not a single picture on it ... Neither the logo (QImage finalLogo) nor the preview (QImage finalPreview).
It's like QPainter::drawText()/drawLine() does work, but not QPainter::drawImage.
It's disturbing since it works on a computer but not on another ... Did I do something wrong when compiling/releasing ?
(Answered in the comments - converted to a community wiki.)
The OP wrote:
Ok ! I figured it out. The dll to handle the jpeg was not in the right directory, I moved it to the right one and it worked.

QSetting trouble

I am working with QSettings function. Once successfully set in the .h file variable
QSettings *settings;
inside the constructor (cpp. file) I set the variable in this way, to obtain a path like Draw/Input/Cells/Width
settings = new QSettings("MySoft", "Star Runner");
settings->beginGroup("Draw");
settings->beginGroup("Input");
settings->beginGroup("Cells");
settings->setValue("width", 80);
settings->endGroup();
settings->endGroup();
settings->endGroup();
The problem is that width value is properly set to 80 only if during the declaration of the organization name is set to "MySoft": if you assign any other value (e.g. "foobar"), doing a test via
qDebug() << settings->value("width", "").toString();
the width key as no value
You should also start and end the groups when reading the value. So you could either try
qDebug() << settings->value("Draw/Input/Cells/width", "").toString();
or
settings->beginGroup("Draw");
settings->beginGroup("Input");
settings->beginGroup("Cells");
qDebug() << settings->value("width", "").toString();
settings->endGroup();
settings->endGroup();
settings->endGroup();

Qt QTextEdit loading just half text file

I have a problem: my project is a very simple one with a QTextEdit and a QSyntaxHighlighter, I'm trying to load a .cpp file and highlighting just the eighth line of that file, but the QTextEdit can't load the entire file if I ask it to highlight the line.
The following image shows the problem:
The relevant code of the application is the following:
void MainWindow::openFile(const QString &path)
{
QString fileName = path;
if (fileName.isNull())
fileName = QFileDialog::getOpenFileName(this,
tr("Open File"), "", "C++ Files (*.cpp *.h)");
if (!fileName.isEmpty()) {
QFile file(fileName);
if (file.open(QFile::ReadOnly | QFile::Text))
editor->setPlainText(file.readAll());
QVector<quint32> test;
test.append(8); // I want the eighth line to be highlighted
editor->highlightLines(test);
}
}
and
#include "texteditwidget.h"
TextEditWidget::TextEditWidget(QWidget *parent) :
QTextEdit(parent)
{
setAcceptRichText(false);
setLineWrapMode(QTextEdit::NoWrap);
}
// Called to highlight lines of code
void TextEditWidget::highlightLines(QVector<quint32> linesNumbers)
{
// Highlight just the first element
this->setFocus();
QTextCursor cursor = this->textCursor();
cursor.setPosition(0);
cursor.movePosition(QTextCursor::Down, QTextCursor::MoveAnchor, linesNumbers[0]);
this->setTextCursor(cursor);
QTextBlock block = document()->findBlockByNumber(linesNumbers[0]);
QTextBlockFormat blkfmt = block.blockFormat();
// Select it
blkfmt.setBackground(Qt::yellow);
this->textCursor().mergeBlockFormat(blkfmt);
}
However if you want to test the project with the cpp file I used (in the directory FileToOpen\diagramwidget.cpp), here's the complete source
http://idsg01.altervista.org/QTextEditProblem.zip
I've been trying to solve this for a lot of time and I'm starting to wonder if this isn't a bug or something similar
The QTextEdit can't accept such a big amount of text at one piece. Split it, for example like this:
if (!fileName.isEmpty()) {
QFile file(fileName);
if (file.open(QFile::ReadOnly | QFile::Text))
{
QByteArray a = file.readAll();
QString s = a.mid(0, 3000);//note that I split the array into pieces of 3000 symbols.
//you will need to split the whole text like this.
QString s1 = a.mid(3000,3000);
editor->setPlainText(s);
editor->append(s1);
}
It seems that the QTextEdit control needs time after each loading, setting a QApplication:processEvents(); after setPlainText() solves the problem although it's not an elegant solution.