I have Qt Resource file (res.qrc) in my Qt Application. I imported my custom font in resource as below:
:/fonts/aa_marcus_east_syriac.ttf
Also i define in header file:
private:
QFont assyrianEventsAAMarcusEastSyriac;
I used QTextEdit in mainwindow. When user click on a button, my application read a text file. every row in text file should be imported in QTextEdit but some lines should be has aa_marcus_east_syriac.ttf font from my resource. So I wrote this codes:
void Widget::readMonthAssyrianEvents()
{
QStringList eventsList;
eventsList = readEventFile();
ui->notificationTextEdit->setCurrentFont(assyrianEventsAAMarcusEastSyriac);
for (int index = 0; index < eventsList.length(); index++)
{
QString eventType, eventContent;
QStringList tempStringList = eventsList[index].split('|');
eventType = tempStringList[0];
eventContent = tempStringList[1];
if (eventType == "0")
ui->notificationTextEdit->append(eventContent);
}
}
readEventFile() function works fine. It read text file and get all lines as QStringList. the "assyrianEventsAAMarcusEastSyriac" variable initialized in another function called init(). this is init() function:
int id = QFontDatabase::addApplicationFont(":/fonts/aa_marcus_east_syriac.ttf");
QString family = QFontDatabase::applicationFontFamilies(id).at(0);
assyrianEventsAAMarcusEastSyriac.setFamily(family);
assyrianEventsAAMarcusEastSyriac.setPointSize(20);
My problem is that QTextEdit doesn't change font of it's contents to my custom font.
How can I solve this problem? Please help me guys.
Thanks
I think the error is in
QString family = QFontDatabase::applicationFontFamilies(id).at(0);
Have you checked that .at(0) is actually your custom font ?
Most likely you can solve this by calling assyrianEventsAAMarcusEastSyriac.setFamily
with an explicit string of the font family just like
assyrianEventsAAMarcusEastSyriac.setFamily("Marcus East Syriac");
If that doesn't work either, maybe your custom font is malformed or doesn't provide a font family name. Therefore I suggest you to try first with a working font and then eventually go back to custom stuff.
Related
I have a problem with the QFileDialog class, namely with the setDirectory() and directory() methods. I need to make it so that after opening a file, my program remembers the directory in which the selected file is stored, and the next time QFileDialog is called, it automatically opens the directory that was used last. Here is a snippet of my code:
static QString _st_doc_last_directory;
void MainWindow::open()
{
if (!fileDialog)
{ fileDialog = new QFileDialog(this);
}
if (!_st_doc_last_directory.isEmpty()) fileDialog->setDirectory(_st_doc_last_directory);
QString fileName = fileDialog->getOpenFileName(this, tr("Open Document"), ".", tr("Compressed CAD Models (*.data)"));
if (!fileName.isEmpty())
{ _st_doc_last_directory = fileDialog->directory().dirName();
}
}
The crux of my problem is that when the setDirectory() or directory() method is called, my program crashes with a
"Segmentation fault"
message. How can I fix it, please advise. Thanks in advance.
Whenever you start this method, you have this as the start window: ".". (admittedly I don't know what's going on internally, but I think this leads to this problem).
You can query beforehand whether your defined string is empty. if so you set a path, otherwise you store one in your string. If you don't want to do this from the beginning every time you start the program, you can also use QSettings. This saves you the path in the registry (ie if you use windows).
With QFileInfo you can easily get the path
void MainWindow::open()
{
if(_st_doc_last_directory.isEmpty())
_st_doc_last_directory = QDir::homePath();
QString fileName = QFileDialog::getOpenFileName(this, tr("Open Document"), _st_doc_last_directory, tr("Compressed CAD Models (*.data)"));
QFileInfo info(fileName);
if(!fileName.isEmpty())
_st_doc_last_directory = info.absolutePath();
}
I successfully managed to compile Qt 4 including WebKit for WinCE. QWebView seems to run fine - I can load a HTML5 document and it gets displayed.
ui.webView->page()->settings()->setAttribute(QWebSettings::JavascriptEnabled, true);
ui.webView->setUrl(QUrl::fromLocalFile(QFileInfo(QLatin1String("test.html")).absoluteFilePath()));
However, as soon as the page contains any JavaScript (even an empty script-tag already causes the problem), QWebView will only display a blank page.
The QWebInspector window can also not be shown, as it also just displays a blank window.
I doubt this is a common problem, so my question is, how I could dig into that issue. Is there any debug log for QWebView?
Unfortunately, there's no exception or assertion failure being thrown while execution.
Any ideas? :)
Thank you in advance.
EDIT:
Here is the test code creating the problem. The first four lines of loadFinished are some test code to check valid pointers and whether I could call methods on QWebFrame at all. All code lines execute well until the evaluateJavaScript, where I get an access violation.
I could not post the HTML code inside setHtml, seems to be forbidden by Stackoverflow.
ce0::ce0(QWidget *parent, Qt::WFlags flags)
: QMainWindow(parent, flags)
{
ui.setupUi(this);
connect(ui.webView, SIGNAL(loadFinished(bool)), SLOT(loadFinished(bool)));
ui.webView->page()->settings()->setAttribute(QWebSettings::LocalContentCanAccessRemoteUrls, true);
ui.webView->page()->settings()->setAttribute(QWebSettings::LocalContentCanAccessFileUrls, true);
ui.webView->page()->settings()->setAttribute(QWebSettings::DeveloperExtrasEnabled, true);
ui.webView->page()->settings()->setAttribute(QWebSettings::JavascriptEnabled, true);
//ui.webView->setUrl(QUrl::fromLocalFile(QFileInfo(QLatin1String("test.html")).absoluteFilePath()));
ui.webView->setHtml(...);
}
void ce0::loadFinished(bool ok) {
QWebPage* p = ui.webView->page();
QWebFrame* f = p->mainFrame();
QString qs = f->title();
bool x = ui.webView->page()->settings()->testAttribute( QWebSettings::JavascriptEnabled );
f->evaluateJavaScript("document.getElementById(\"content\").innerHTML = \"Whatever\";");
}
I have a subclass of QTextDocument that overrides QTextDocument::loadResource(int type, const QUrl &name).
I want to clone it.
Ideas ?
You can't use QTextDocument::clone for that. Neither can you reimplement it because it's not virtual. You should create another clone method (you can name it clone but I'd give it another name to avoid confusion) and implement cloning yourself. You can use toHtml and setHtml to copy content from one object to another:
MyTextDocument* MyTextDocument::my_clone(QObject * parent = 0) {
MyTextDocument* other = new MyTextDocument(parent);
other->setHtml(toHtml());
return other;
}
There are however many other properties that should be copied. See how QTextDocument::clone method is implemented:
QTextDocument *QTextDocument::clone(QObject *parent) const
{
Q_D(const QTextDocument);
QTextDocument *doc = new QTextDocument(parent);
QTextCursor(doc).insertFragment(QTextDocumentFragment(this));
doc->rootFrame()->setFrameFormat(rootFrame()->frameFormat());
QTextDocumentPrivate *priv = doc->d_func();
priv->title = d->title;
priv->url = d->url;
priv->pageSize = d->pageSize;
priv->indentWidth = d->indentWidth;
priv->defaultTextOption = d->defaultTextOption;
priv->setDefaultFont(d->defaultFont());
priv->resources = d->resources;
priv->cachedResources.clear();
#ifndef QT_NO_CSSPARSER
priv->defaultStyleSheet = d->defaultStyleSheet;
priv->parsedDefaultStyleSheet = d->parsedDefaultStyleSheet;
#endif
return doc;
}
If these properties are important to you, you need to copy them manually in your my_clone implementation. You can're use QTextDocumentPrivate class because it's internal. So you can't just copy default implementation. But there is a normal way to set each of listed properties in the API.
Be aware of forward compability issues. If new properties appeared in newer Qt versions, your implementation will not copy them in opposite to default clone implementation. That could be a problem so this approach is not perfect.
I am currently working on a code editor written in Qt,
I have managed to implement most of the features which I desire, i.e. auto completion and syntax highlighting but there is one problem which I can't figure out.
I have created a model for which the QCompleter uses, which is fine for things like html tags and c++ keywords such as if else etc.
But I would like to add variables to the completer as they are entered by the user.
So I created an event on the QTextEdit which will get the word (I know I need to check to make sure that it is a variable etc but I just want to get it working for now).
void TextEdit::checkWord()
{
//going to get the previous word and try to do something with it
QTextCursor tc = textCursor();
tc.movePosition(QTextCursor::PreviousWord);
tc.select(QTextCursor::WordUnderCursor);
QString word = tc.selectedText();
//check to see it is in the model
}
But now I want to work out how to check to see if that word is already in the QCompleters model and if it isn't how do I add it?
I have tried the following:
QAbstractItemModel *m = completer->model();
//dont know what to do with it now :(
You can check if word is in your QCompleter really by using
QAbstractItemModel *m = completer->model();
as you can see, method model() returns const pointer.
That is good for checking procedure, you can check like this:
bool matched = false;
QString etalon("second");
QStringListModel *strModel = qobject_cast<QStringListModel*>(completer.model());
if (strModel!=NULL)
foreach (QString str, strModel->stringList()) {
if (str == etalon)
{
matched = true;
break;
}
}
qDebug()<<matched;
But for your purposes, I recommend you to declare QStringListModel, and connect it to your completer, and then, all of operations you'll must do thru your model, according to Qt's principles of MVC programming (http://doc.qt.digia.com/qt/model-view-programming.html).
Your code can be like this:
// declaration
QCompleter completer;
QStringListModel completerModel;
// initialization
completer.setModel(&completerModel);
QStringList stringListForCompleter;
stringListForCompleter << "first" << "second" << "third";
completerModel.setStringList(stringListForCompleter);
// adding new word to your completer list
completerModel.setStringList(completerModel.stringList() << "New Word");
Good luck!
I'm having a bit of trouble with my function for displaying pdf's with the poppler library. The code below is the function in which the problem occurs.
const QString &file is the path to the file
int page is the page on which it has to open
When i set file to a real path (e.g. "/Users/User/Documents/xxx.pdf"), it is no problem to open it. But when i give the path to a qrc file (":/files/xxx.pdf"), it won't work. I want to use it for displaying a user manual for instance, within the application.
I've also tried first making a QFile out of it, opening it and doing readAll, then loading the QByteArray received by doingPoppler::Document::loadFromData(the qbytearray), but it errors already when opening the QFile in ReadOnly mode.
void class::setPdf(const QString &file, int page)
{
Poppler::Document *doc = Poppler::Document::load(file);
if (!doc) {
QMessageBox msgbox(QMessageBox::Critical, tr("Open Error"), tr("Please check preferences: cannot open:\n") + file,
QMessageBox::Ok, this);
msgbox.exec();
}
else{ /*Code for displaying the pdf, which works fine*/
}
}
I hope you can help me,
greetings,
Matt
I've also tried first making a QFile
out of it, opening it and doing
readAll, then loading the QByteArray
received by
doingPoppler::Document::loadFromData(the
qbytearray), but it errors already
when opening the QFile in ReadOnly
mode.
QFile f;
f.setFileName(":/skin/AppIcon16.png");
f.open(QIODevice::ReadOnly);
QByteArray r=f.readAll();
Perfectly reads all data from the resource, have checked it. So i suggest you did something wrong when tried that. Maybe path errors, maybe something else...