16.2. Использование QTextBrowser для отображения текста справки.
Большие серьезные приложения могут содержать объем справочной информации, намного превышающий возможности всплывающих подсказок и даже подсказок типа «What’s This?». Самое простое решение в этом случае — создать обозреватель справочной системы. Приложение может открывать окно обозревателя справки при выборе пункта Help, в меню Help, или при нажатии на кнопку Help в панели инструментов.
В этом разделе мы рассмотрим простейший обозреватель справочной системы, внешний вид которого представлен на рисунке 16.3, и опишем, как его использовать в приложении. Для отображения текста справки используется QTextBrowser, который может обрабатывать некоторые теги HTML и идеально подходит под заданные условия.
Рисунок 16.3. Виджет HelpBrowser.
Как обычно, начнем с заголовочного файла:
#include class QPushButton; class QTextBrowser; class HelpBrowser : public QWidget < Q_OBJECT public: HelpBrowser(const QString &path, const QString &page, QWidget *parent = 0, const char *name = 0); static void showPage(const QString &page); private slots: void updateCaption(); private: QTextBrowser *textBrowser; QPushButton *homeButton; QPushButton *backButton; QPushButton *closeButton; >;
HelpBrowser имеет статическую функцию, которая может вызываться из любого места в приложении. Она создает окно обозревателя и показывает запрошенную страницу.
Теперь исходный код файла реализации:
#include #include #include #include #include "helpbrowser.h" HelpBrowser::HelpBrowser(const QString &path, const QString &page, QWidget *parent, const char *name) : QWidget(parent, name, WGroupLeader | WDestructiveClose) < textBrowser = new QTextBrowser(this); homeButton = new QPushButton(tr("&Home"), this); backButton = new QPushButton(tr("&Back"), this); closeButton = new QPushButton(tr("Close"), this); closeButton->setAccel(tr("Esc")); QVBoxLayout *mainLayout = new QVBoxLayout(this); QHBoxLayout *buttonLayout = new QHBoxLayout(mainLayout); buttonLayout->addWidget(homeButton); buttonLayout->addWidget(backButton); buttonLayout->addStretch(1); buttonLayout->addWidget(closeButton); mainLayout->addWidget(textBrowser); connect(homeButton, SIGNAL(clicked()), textBrowser, SLOT(home())); connect(backButton, SIGNAL(clicked()), textBrowser, SLOT(backward())); connect(closeButton, SIGNAL(clicked()), this, SLOT(close())); connect(textBrowser, SIGNAL(sourceChanged(const QString &)), this, SLOT(updateCaption())); textBrowser->mimeSourceFactory()->addFilePath(path); textBrowser->setSource(page); >
Размещение компонентов в окне более чем простое: ряд кнопок находится над QTextBrowser. Аргумент path — это путь к каталогу, где находятся файлы с текстом справки. Аргумент page — имя файла справки, с необязательным названием темы (в терминах HTML — anchor, или имя ссылки).
Мы передаем конструктору флаг WGroupLeader, потому что окно HelpBrowser может открываться из модальных диалогов. Обычно модальные диалоги не позволяют пользователю взаимодействовать с другими окнами приложения. Однако, в данном случае, после того как пользователь запросил помощь, он должен иметь возможность работать как с окном модального диалога, так и с окном обозревателя справочной системы. Флаг WGroupLeader обеспечивает такую возможность.
void HelpBrowser::updateCaption() < setCaption(tr("Help: %1").arg(textBrowser->documentTitle())); >
Всякий раз, при переходе на другую страницу, вызывается слот updateCaption(). Функция documentTitle() возвращает текст, заданный в теге .
void HelpBrowser::showPage(const QString &page) < QString path = qApp->applicationDirPath() + "/doc"; HelpBrowser *browser = new HelpBrowser(path, page); browser->resize(500, 400); browser->show(); >
В функции showPage() создается окно обозревателя и затем выводится на экран. Окно будет уничтожено автоматически, когда пользователь закроет его, поскольку в конструкторе был установлен флаг WDestructiveClose.
В данном примере мы исходим из предположения, что файлы справки находятся в подкаталоге doc.
Теперь можно вызвать обозреватель из приложения. Для этого, в главном окне приложения, мы создадим объект QAction -- Help и соединим его со слотом help():
void MainWindow::help()
Мы полагаем, что основной файл справки называется index.html. Чтобы вызвать обозреватель из диалога, нужно связать соответствующую кнопку Help со слотом help():
void EntryDialog::help()
Здесь мы обращаемся уже к другому файлу справки -- dialogs.html и выполняем переход к ссылке entrydialog.
Еще одно место, откуда можно вызвать обозреватель справочной системы -- текст справки типа "What's This?". Для этого достаточно вставить в текст справки "What's This?" тег HTML .
Рисунок 16.4. Текст справки "What's This?" со ссылкой на файл справки.
Чтобы такая гипертекстовая ссылка работала, мы должны использовать класс, производный от QWhatsThis, который будет "знать", как вызвать обозреватель справочной системы. Для этого надо в классе-потомке перекрыть метод clicked(), в котором вызвать HelpBrowser:: showPage(). Ниже приводится определение класса:
class MyWhatsThis : public QWhatsThis < public: MyWhatsThis(QWidget *widget, const QString &text); QString text(const QPoint &point); bool clicked(const QString &page); private: QString myText; >;
Где text() и clicked() -- это методы предка, перекрываемые потомком.
MyWhatsThis::MyWhatsThis(QWidget *widget, const QString &text) : QWhatsThis(widget)
Конструктор получает указатель на виджет и текст справки для этого виджета. Мы передаем указатель на виджет базовому конструктору и сохраняем текст справки в приватной переменной.
QString MyWhatsThis::text(const QPoint &)
Функция text() возвращает текст справки виджета, для заданных координат указателя мыши. Некоторые виджеты могут возвращать разный текст справки, в зависимости от того, где был произведен щелчок мышью, но в данном примере мы всегда будем возвращать один и тот же текст.
bool MyWhatsThis::clicked(const QString &page) < if (page.isEmpty()) < return true; >else < HelpBrowser::showPage(page); return false; >>
Функция clicked() вызывается в момент щелчка мышью по виджету, когда окно находится в режиме "What's This?". Если пользователь щелкает по гиперссылке, то функция получит название страницы в аргументе page. В противном случае в page будет пустая строка.
Возвращаемое значение используется базовым классом QWhatsThis для того, чтобы определить, что делать дальше -- скрыть (true) подсказку "What's This?" или оставить ее видимой (false). В данной ситуации мы хотим, чтобы текст "What's This?" оставался видимым на экране, поэтому возвращаем false. Когда пользователь щелкает по любому другому месту в тексте "What's This?", мы возвращаем true.
Ниже показан пример использования класса MyWhatsThis:
new MyWhatsThis(sourceLineEdit, tr("" " The meaning of the " "Source field depends on " "the Type field:" "
-
" "
- Books have a Publisher" "
- Articles have a Journal name with volume and " "issue number" "
- Thesis have an Institution name and a department " "name" "
На этот раз, вместо вызова QWhatsThis::add(), мы создаем экземпляр класса MyWhatsThis для виджета, с текстом подсказки. Теперь пользователь может щелкнуть по гипертекстовой ссылке и вызвать обозреватель справочной системы.
Выглядит немного странно, так как мы создаем объект, но не связываем его с какой бы то ни было переменной. Но это только на первый взгляд, потому что Qt сама следит за создаваемыми объектами класса QWhatsThis и удаляет их, когда необходимость в них отпадает.
Пред. | В начало | След. |
Разработка справочной системы приложения. | На уровень выше | Использование Qt Assistant для отображения текста справки. |
Qtextbrowser форматирование текста
Добрый день!
У меня есть итоговая строка, я ее вывожу в qtextbrowser.
Как сделать чтобы фрагментами делать текст жирным , а другие фрагменты не трогать?
Может есть какой то метод чтобы как то формировать итоговую строку?
Заранее спасибо!
Добавлено через 4 минуты
Так, по этой ссылке понимаю, что лучше не формировать строку и ее отображать, а как тут :
через append добавлять информацию. Перед этим ее форматируя. Подскажите тогда как форматировать))
Добавлено через 52 секунды
Так?
QString str="text"; QString str1="text1"; QString str2="text2"; ui->lbl_text1->setText(str); ui->lbl_text2->setText(str1); ui->lbl_text3->setText(str2); ui->lbl_text1->setFont(QFont("Times", 10)); ui->lbl_text2->setFont(QFont("Times", 12, 1, 1)); ui->lbl_text3->setFont(QFont("Times", 13, 100, 0));
Добавлено через 23 минуты
Хотя подождите, тогда будет формат всего текста меняться.
Вопрос актуальный: как сделать участок строки жирным шрифтом, остальные обычным.
Добавлено через 1 час 11 минут
А может вот так : setHtml(text);
Где текст уже отформатирован в стиле HTML?
Я так понял для этого надо расставить вот так Текст
Как добавить текст в qtextbrowser в qt
На этом шаге рассмотрим класс QTextEdit многострочного текстового редактора.
Класс QTextEdit позволяет осуществлять просмотр и редактирование как простого текста, так и текста в формате HTML. Он унаследован от класса QAbstractScrollArea, что дает возможность автоматически отображать полосы прокрутки, если текст не может быть полностью отображен в отведенной для него области.
Если вам нужен редактор для обычного текста, то целесообразнее будет воспользоваться вместо класса QTextEdit классом QPlaintTextEdit. Класс QPlaintTextEdit не поддерживает RTF (Rich Text Format, формат обогащенного текста), в силу чего является более легковесным, простым и эффективным.
Класс QTextEdit содержит следующие методы:
- setReadOnly() устанавливает или снимает режим блокировки изменения текста;
- text() возвращает текущий текст.
Слоты класса QTextEdit:
- setPlainText() — установка обычного текста;
- setHtml() — установка текста в формате HTML;
- copy(), cut() и paste() — работа с буфером обмена (копировать, вырезать и вставить соответственно);
- selectAll() или deselect() — выделение или снятие выделения всего текста;
- clear() — очистка поля ввода.
- textChanged() — отправляется при изменении текста;
- selectionChanged() — отправляется при изменениях выделения текста.
Для работы с выделенным текстом служит класс QTextCursor, и объект этого класса содержится в классе QTextEdit. Класс QTextCursor предоставляет методы для создания участков выделения текста, получения содержимого выделенного текста и его удаление.
Указатель на объект класса QTextCursor можно получить вызовом метода QTextEdit::textCursor().
Виджеты класса QTextEdit также содержат в себе объект QTextDocument, указатель на который можно получить посредством метода QTextEdit::document(). Можно также присвоить другой документ при помощи метода QTextEdit::setDocument().
Класс QTextDocument предоставляет слот undo() (для отмены) или redo() (для повтора действий). При вызове слотов undo() и redo() посылаются сигналы undoAvailable(bool) и redoAvailable(bool), сообщающие об успешном (или безуспешном) проведении операции. Эти сигналы отправляются как из класса QTextDocument, так и из QTextEdit. В большинстве случаев удобнее будет использовать сигналы класса QTextEdit.
Большинство методов класса QTextEdit являются делегирующими для класса QTextDocument. Например, как уже было сказано ранее, класс QTextEdit способен отображать файлы с кодом на языке HTML, содержащие таблицы и растровые изображения. Для его размещения и показа можно воспользоваться методом setHtml(), в который передается строка, содержащая в себе текст в формате HTML, или воспользоваться слотом insertHtml(). Эти методы определены в обоих классах, и их вызов из объекта класса QTextEdit приведет к тому, что будет вызван аналогичный метод из объекта класса QTextDocument.
Для помещения обычного текста в область виджета можно воспользоваться методом setPlainText() или слотом insertPlainText(). При помощи слота append() осуществляется добавление текста, причем добавленный текст не вносится в список операций, действие которых можно вернуть с помощью слота undo(), что делает этот слот быстрым и не требующим дополнительных затрат памяти. Метод find() может быть использован для поиска и выделения заданной строки в тексте.
Слоты zoomIn() и zoomOut() предназначены для увеличения или уменьшения размера шрифта, и их действие не распространяется на растровые изображения.
Приведенный на рис. 1 пример отображает HTML-документ. Текст документа можно редактировать.
Рис.1. Пример отображения HTML-документа
В листинге приводится фрагмент текста из файла приложения, окно которого показано на рис. 1:
-
" "
- setReadOnly() устанавливает или снимает режим блокировки изменения текста;" "
- text() возвращает текущий текст." "
-
" "
- setPlainText() — установка обычного текста;" "
- setHtml() — установка текста в формате HTML;" "
- copy(), cut() и paste() — работа с буфером обмена (копировать, вырезать и вставить соответственно);" "
- selectAll() или deselect() — выделение или снятие выделения всего текста;" "
- clear() — очистка поля ввода." "
Файлы приложения можно взять здесь.
На следующем шаге рассмотрим запись содержимого объекта в файл.
QTextBrowser Class
This class extends QTextEdit (in read-only mode), adding some navigation functionality so that users can follow links in hypertext documents.
If you want to provide your users with an editable rich text editor, use QTextEdit. If you want a text browser without hypertext navigation use QTextEdit, and use QTextEdit::setReadOnly() to disable editing. If you just need to display a small piece of rich text use QLabel.
Document Source and Contents
The contents of QTextEdit are set with setHtml() or setPlainText(), but QTextBrowser also implements the setSource() function, making it possible to use a named document as the source text. The name is looked up in a list of search paths and in the directory of the current document factory.
If a document name ends with an anchor (for example, " #anchor" ), the text browser automatically scrolls to that position (using scrollToAnchor()). When the user clicks on a hyperlink, the browser will call setSource() itself with the link's href value as argument. You can track the current source by connecting to the sourceChanged() signal.
Navigation
QTextBrowser provides backward() and forward() slots which you can use to implement Back and Forward buttons. The home() slot sets the text to the very first document displayed. The anchorClicked() signal is emitted when the user clicks an anchor. To override the default navigation behavior of the browser, call the setSource() function to supply new document text in a slot connected to this signal.
If you want to load documents stored in the Qt resource system use qrc as the scheme in the URL to load. For example, for the document resource path :/docs/index.html use qrc:/docs/index.html as the URL with setSource().
Property Documentation
[read-only] modified : const bool
This property holds whether the contents of the text browser have been modified
openExternalLinks : bool
Specifies whether QTextBrowser should automatically open links to external sources using QDesktopServices::openUrl() instead of emitting the anchorClicked signal. Links are considered external if their scheme is neither file or qrc.
The default value is false.
Access functions:
bool | openExternalLinks () const |
void | setOpenExternalLinks (bool open) |
openLinks : bool
This property specifies whether QTextBrowser should automatically open links the user tries to activate by mouse or keyboard.
Regardless of the value of this property the anchorClicked signal is always emitted.
The default value is true.
Access functions:
bool | openLinks () const |
void | setOpenLinks (bool open) |
readOnly : const bool
This property holds whether the text browser is read-only
By default, this property is true .
searchPaths : QStringList
This property holds the search paths used by the text browser to find supporting content
QTextBrowser uses this list to locate images and documents.
By default, this property contains an empty string list.
Access functions:
QStringList | searchPaths () const |
void | setSearchPaths (const QStringList &paths) |
source : QUrl
This property holds the name of the displayed document.
This is a an invalid url if no document is displayed or if the source is unknown.
When setting this property QTextBrowser tries to find a document with the specified name in the paths of the searchPaths property and directory of the current source, unless the value is an absolute file path. It also checks for optional anchors and scrolls the document accordingly
If the first tag in the document is , the document is displayed as a popup rather than as new document in the browser window itself. Otherwise, the document is displayed normally in the text browser with the text set to the contents of the named document with QTextDocument::setHtml() or QTextDocument::setMarkdown(), depending on whether the filename ends with any of the known Markdown file extensions.
If you would like to avoid automatic type detection and specify the type explicitly, call setSource() rather than setting this property.
By default, this property contains an empty URL.
Access functions:
QUrl | source () const |
void | setSource (const QUrl &url, QTextDocument::ResourceType type = QTextDocument::UnknownResource) |
[read-only] sourceType : const QTextDocument::ResourceType
This property holds the type of the displayed document
This is QTextDocument::UnknownResource if no document is displayed or if the type of the source is unknown. Otherwise it holds the type that was detected, or the type that was specified when setSource() was called.
Access functions:
QTextDocument::ResourceType | sourceType () const |
undoRedoEnabled : const bool
This property holds whether the text browser supports undo/redo operations
By default, this property is false .
Member Function Documentation
[explicit] QTextBrowser:: QTextBrowser ( QWidget *parent = nullptr)
Constructs an empty QTextBrowser with parent parent.
[signal] void QTextBrowser:: anchorClicked (const QUrl &link)
This signal is emitted when the user clicks an anchor. The URL referred to by the anchor is passed in link.
Note that the browser will automatically handle navigation to the location specified by link unless the openLinks property is set to false or you call setSource() in a slot connected. This mechanism is used to override the default navigation features of the browser.
[virtual slot] void QTextBrowser:: backward ()
Changes the document displayed to the previous document in the list of documents built by navigating links. Does nothing if there is no previous document.
[signal] void QTextBrowser:: backwardAvailable ( bool available)
This signal is emitted when the availability of backward() changes. available is false when the user is at home(); otherwise it is true.
int QTextBrowser:: backwardHistoryCount () const
Returns the number of locations backward in the history.
void QTextBrowser:: clearHistory ()
Clears the history of visited documents and disables the forward and backward navigation.
[virtual protected] void QTextBrowser:: doSetSource (const QUrl &url, QTextDocument::ResourceType type = QTextDocument::UnknownResource)
Attempts to load the document at the given url with the specified type.
setSource() calls doSetSource. In Qt 5, setSource(const QUrl &url) was virtual. In Qt 6, doSetSource() is virtual instead, so that it can be overridden in subclasses.
[override virtual protected] bool QTextBrowser:: event ( QEvent *e)
[override virtual protected] bool QTextBrowser:: focusNextPrevChild ( bool next)
[override virtual protected] void QTextBrowser:: focusOutEvent ( QFocusEvent *ev)
[virtual slot] void QTextBrowser:: forward ()
Changes the document displayed to the next document in the list of documents built by navigating links. Does nothing if there is no next document.
[signal] void QTextBrowser:: forwardAvailable ( bool available)
This signal is emitted when the availability of forward() changes. available is true after the user navigates backward() and false when the user navigates or goes forward().
int QTextBrowser:: forwardHistoryCount () const
Returns the number of locations forward in the history.
[signal] void QTextBrowser:: highlighted (const QUrl &link)
This signal is emitted when the user has selected but not activated an anchor in the document. The URL referred to by the anchor is passed in link.
[signal] void QTextBrowser:: historyChanged ()
This signal is emitted when the history changes.
QString QTextBrowser:: historyTitle ( int i) const
Returns the documentTitle() of the HistoryItem.
Input | Return |
---|---|
i < 0 | backward() history |
i == 0 | current, see QTextBrowser::source() |
i > 0 | forward() history |
backaction.setToolTip(browser.historyTitle(-1)); forwardaction.setToolTip(browser.historyTitle(+1));
QUrl QTextBrowser:: historyUrl ( int i) const
Returns the url of the HistoryItem.
Input | Return |
---|---|
i < 0 | backward() history |
i == 0 | current, see QTextBrowser::source() |
i > 0 | forward() history |
[virtual slot] void QTextBrowser:: home ()
Changes the document displayed to be the first document from the history.
bool QTextBrowser:: isBackwardAvailable () const
Returns true if the text browser can go backward in the document history using backward().
bool QTextBrowser:: isForwardAvailable () const
Returns true if the text browser can go forward in the document history using forward().
[override virtual protected] void QTextBrowser:: keyPressEvent ( QKeyEvent *ev)
The event ev is used to provide the following keyboard shortcuts:
Keypress | Action |
---|---|
Alt+Left Arrow | backward() |
Alt+Right Arrow | forward() |
Alt+Up Arrow | home() |
[override virtual] QVariant QTextBrowser:: loadResource ( int type, const QUrl &name)
Reimplements: QTextEdit::loadResource(int type, const QUrl &name).
This function is called when the document is loaded and for each image in the document. The type indicates the type of resource to be loaded. An invalid QVariant is returned if the resource cannot be loaded.
The default implementation ignores type and tries to locate the resources by interpreting name as a file name. If it is not an absolute path it tries to find the file in the paths of the searchPaths property and in the same directory as the current source. On success, the result is a QVariant that stores a QByteArray with the contents of the file.
If you reimplement this function, you can return other QVariant types. The table below shows which variant types are supported depending on the resource type:
ResourceType | QMetaType::Type |
---|---|
QTextDocument::HtmlResource | QString or QByteArray |
QTextDocument::ImageResource | QImage, QPixmap or QByteArray |
QTextDocument::StyleSheetResource | QString or QByteArray |
QTextDocument::MarkdownResource | QString or QByteArray |
[override virtual protected] void QTextBrowser:: mouseMoveEvent ( QMouseEvent *e)
[override virtual protected] void QTextBrowser:: mousePressEvent ( QMouseEvent *e)
[override virtual protected] void QTextBrowser:: mouseReleaseEvent ( QMouseEvent *e)
[override virtual protected] void QTextBrowser:: paintEvent ( QPaintEvent *e)
[virtual slot] void QTextBrowser:: reload ()
Reloads the current set source.
[slot] void QTextBrowser:: setSource (const QUrl &url, QTextDocument::ResourceType type = QTextDocument::UnknownResource)
Attempts to load the document at the given url with the specified type.
If type is UnknownResource (the default), the document type will be detected: that is, if the url ends with an extension of .md , .mkd or .markdown , the document will be loaded via QTextDocument::setMarkdown(); otherwise it will be loaded via QTextDocument::setHtml(). This detection can be bypassed by specifying the type explicitly.
Note: Setter function for property source.
[signal] void QTextBrowser:: sourceChanged (const QUrl &src)
This signal is emitted when the source has changed, src being the new source.
Source changes happen both programmatically when calling setSource(), forward(), backward() or home() or when the user clicks on links or presses the equivalent key sequences.
© 2023 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.