Как добавить текст в qtextbrowser в qt

от admin

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 <qt type=detail> , 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

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.

[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().

[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.

[virtual slot] void QTextBrowser:: home ()

Changes the document displayed to be the first document from the history.

[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.

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)

int QTextBrowser:: forwardHistoryCount () const

Returns the number of locations forward in the history.

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

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

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:

Как добавить текст в QTextBrowser в QT?

Я создал QTextBrowser для отображения большого количества данных (фактически отображающих журнал времени выполнения), которые динамически генерируются в других процессах.

Я обнаружил, что могу использовать fopen(«log.html»,»a») для добавления данных в фактический файл журнала и reload() он каждый раз обновляется, но я думаю, что это неэффективно или даже, возможно, неразумно.

Интересно, есть ли какой-нибудь изящный способ реализовать это.

Если вам нужна более производительная версия добавления, вам нужно доступ к внутреннему QTextDocument. — savolai ᯓ

2 ответы

QTextBrowser наследуется QTextEdit , так что вы можете использовать QTextEdit::append :

Все же разрешите поблагодарить вас! однако я не знаю, как выбрать несколько ответов — Iloahz

@Topro: может быть только один принятый ответ (с зеленой галочкой), но вы можете проголосовать за столько ответов, сколько захотите. Для этого вы должны щелкнуть маленький треугольник, указывающий вверх, слева от ответа. Точно так же, если вы считаете, что ответ неправильный или не содержит полезной информации, вы можете проголосовать против него, указав треугольник, направленный вниз. — Люк Турель

Написал наполовину это дополнение к ответу TonyK:

Возможно, добавлять Метод — это то, что вы ищете?

Добавляет новый абзац с текстом в конец редактирования текста. Новый добавленный абзац будет иметь тот же формат символов и формат блока, что и текущий абзац, что определяется положением курсора. Смотрите также currentCharFormat () и QTextCursor :: blockFormat ().

QTextBrowser Class

Этот класс расширяет QTextEdit (в режиме только для чтения), добавляя некоторые функции навигации, чтобы пользователи могли переходить по ссылкам в гипертекстовых документах.

Если вы хотите предоставить своим пользователям редактируемый редактор форматированного текста, используйте QTextEdit . Если вам нужен текстовый браузер без гипертекстовой навигации, используйте QTextEdit и используйте QTextEdit::setReadOnly (), чтобы отключить редактирование. Если вам просто нужно отобразить небольшой фрагмент форматированного текста, используйте QLabel .

Источник и содержание документа

Содержимое QTextEdit устанавливается с помощью setHtml () или setPlainText (), но QTextBrowser также реализует функцию setSource (), позволяющую использовать именованный документ в качестве исходного текста. Имя ищется в списке путей поиска и в каталоге текущей фабрики документов.

Если имя документа заканчивается привязкой (например, » #anchor» ), текстовый браузер автоматически прокручивается до этой позиции (используя scrollToAnchor ()). Когда пользователь щелкает гиперссылку, браузер сам вызывает setSource () со значением href ссылки в качестве аргумента. Вы можете отслеживать текущий источник, подключившись к сигналу sourceChanged ().

Navigation

QTextBrowser предоставляет слоты backward () и forward (), которые вы можете использовать для реализации кнопок Back и Forward. В доме () устанавливает слот текст для самого первого документа отображается. Сигнал anchorClicked () испускается, когда пользователь щелкает привязку . Чтобы переопределить поведение навигации браузера по умолчанию, вызовите функцию setSource (), чтобы предоставить новый текст документа в слот, связанный с этим сигналом.

Если вы хотите загрузить документы, хранящиеся в системе ресурсов Qt, используйте qrc в качестве схемы в URL для загрузки. Например, для пути к ресурсу документа :/docs/index.html используйте qrc:/docs/index.html в качестве URL-адреса с помощью setSource ().

Property Documentation

[read-only] изменено: const bool

Это свойство определяет,было ли изменено содержимое текстового браузера

openExternalLinks : bool

Определяет, должен ли QTextBrowser автоматически открывать ссылки на внешние источники с помощью QDesktopServices :: openUrl () вместо передачи сигнала anchorClicked . Ссылки считаются внешними, если их схема не является файловой или qrc.

Значение по умолчанию равно false.

Access functions:

bool openExternalLinks() const
void setOpenExternalLinks(bool open )

openLeft:bool

Это свойство указывает, должен ли QTextBrowser автоматически открывать ссылки, которые пользователь пытается активировать с помощью мыши или клавиатуры.

Независимо от значения этого свойства всегда выдается сигнал anchorClicked .

Значение по умолчанию равно true.

Access functions:

bool openLinks() const
void setOpenLinks(bool open )

только для чтения:const bool

Это свойство определяет,доступен ли текстовый браузер только для чтения.

По умолчанию это свойство true .

searchPaths : QStringList

Это свойство содержит поисковые пути,используемые текстовым браузером для поиска поддерживающего контента

QTextBrowser использует этот список для поиска изображений и документов.

По умолчанию это свойство содержит список пустых строк.

Access functions:

QStringList searchPaths() const
void setSearchPaths(const QStringList & paths )

источник: QUrl

Это свойство содержит имя отображаемого документа.

Это неверный url,если документ не отображается или если источник неизвестен.

При установке этого свойства QTextBrowser пытается найти документ с указанным именем в дорожках SearchPaths собственности и каталог текущего источника, если значение не абсолютный путь к файлу. Он также проверяет наличие дополнительных привязок и соответственно прокручивает документ.

Если первым тегом в документе является <qt type=detail> , документ отображается как всплывающее окно, а не как новый документ в самом окне браузера. В противном случае документ нормально отображается в текстовом браузере с текстом, установленным в соответствии с содержимым именованного документа с помощью QTextDocument::setHtml () или QTextDocument::setMarkdown (), в зависимости от того, заканчивается ли имя файла каким-либо из известных файлов Markdown. расширения.

Если вы хотите избежать автоматического определения типа и явно указать тип, вызовите setSource (), а не задавайте это свойство.

По умолчанию это свойство содержит пустой URL.

Access functions:

QUrl source() const
void setSource(const QUrl & url , QTextDocument::ResourceType type = QTextDocument::UnknownResource)

[read-only] sourceType : const QTextDocument::ResourceType

Это свойство содержит тип отображаемого документа

Это QTextDocument :: UnknownResource, если документ не отображается или если тип источника неизвестен. В противном случае он содержит тип, который был обнаружен, или тип, который был указан при вызове setSource ().

Access functions:

QTextDocument::ResourceType sourceType() const

отмененоРе «оВключено:const bool

Это свойство определяет,поддерживает ли браузер текста операции отмены/перезапуска

По умолчанию это свойство имеет значение false .

Документация по функциям члена

QTextBrowser::QTextBrowser(QWidget * parent = nullptr)

Конструирует пустой QTextBrowser с родителем parent .

[signal] void QTextBrowser::anchorClicked(const QUrl & link )

Этот сигнал подается,когда пользователь нажимает на якорь.URL,на который ссылается якорь,передается в link .

Обратите внимание,что браузер будет автоматически обрабатывать навигацию к месту,указанному в параметрах link если для свойства openLinks не задано значение false или вы не вызываете setSource () в подключенном слоте. Этот механизм используется для переопределения функций навигации по умолчанию в браузере.

[virtual slot] void QTextBrowser::backward()

Изменяет отображаемый документ на предыдущий в списке документов,построенных по навигационным ссылкам.Ничего не делает,если нет предыдущего документа.

[signal] void QTextBrowser::backwardAvailable(bool available )

Этот сигнал испускается, когда доступность backward () изменяется. available ложно, когда пользователь находится дома (); в противном случае это правда.

[virtual slot] void QTextBrowser::forward()

Изменяет отображаемый документ на следующий в списке документов,построенных по навигационным ссылкам.Ничего не делает,если нет следующего документа.

[signal] void QTextBrowser::forwardAvailable(bool available )

Этот сигнал испускается, когда доступность forward () изменяется. available имеет значение true после того, как пользователь переходит назад () и false, когда пользователь переходит или идет вперед ().

[signal] void QTextBrowser::highlighted(const QUrl & link )

Этот сигнал подается,когда пользователь выбрал,но не активировал якорь в документе.URL,на который ссылается якорь,передается в формате link .

[signal] void QTextBrowser::historyChanged()

Этот сигнал подается при изменении истории.

[virtual slot] void QTextBrowser::home()

Изменяет отображаемый документ как первый документ из истории.

[virtual slot] void QTextBrowser::reload()

Перезагружает источник тока.

[slot] void QTextBrowser::setSource(const QUrl & url , QTextDocument::ResourceType type = QTextDocument::UnknownResource)

Попытка загрузить документ в заданном url с указанным type .

If type является UnknownResource (по умолчанию), тип документа будет обнаружен: то есть, если URL-адрес заканчивается расширением .md , .mkd или .markdown , документ будет загружен через QTextDocument::setMarkdown (); иначе он будет загружен через QTextDocument::setHtml (). Это обнаружение можно обойти, указав type explicitly.

Примечание. Функция установки для источника свойств .

[signal] void QTextBrowser::sourceChanged(const QUrl & src )

Этот сигнал подается при изменении источника, src будучи новым источником.

Изменения источника происходят как программно при вызове setSource (), forward (), back ( ) или home (), так и когда пользователь щелкает ссылки или нажимает эквивалентные последовательности клавиш.

int QTextBrowser::backwardHistoryCount() const

Возвращает количество мест в истории назад.

void QTextBrowser::clearHistory()

Очищает историю посещенных документов и отключает прямую и обратную навигацию.

[virtual protected] void QTextBrowser::doSetSource(const QUrl & url , QTextDocument::ResourceType type = QTextDocument::UnknownResource)

Попытка загрузить документ в заданном url с указанным type .

setSource () вызывает doSetSource. В Qt 5 setSource (const QUrl & url) был виртуальным. В Qt 6 doSetSource () вместо этого является виртуальным, поэтому его можно переопределить в подклассах.

[override virtual protected] bool QTextBrowser::event(QEvent * e )

[override virtual protected] bool QTextBrowser::focusNextPrevChild(bool next )

[override virtual protected] void QTextBrowser::focusOutEvent(QFocusEvent * ev )

int QTextBrowser::forwardHistoryCount() const

Возвращает количество мест в истории вперед.

QString QTextBrowser::historyTitle(int i ) const

Возвращает documentTitle () объекта HistoryItem.

Input Return
i < 0 backward() history
i == 0 current, см. QTextBrowser :: source ()
i > 0 forward() history

QUrl QTextBrowser::historyUrl(int i ) const

Возвращает урну «Истории».

Input Return
i < 0 backward() history
i == 0 current, см. QTextBrowser :: source ()
i > 0 forward() history

bool QTextBrowser::isBackwardAvailable() const

Возвращает true , если текстовый браузер может вернуться назад по истории документа с помощью backward ().

bool QTextBrowser::isForwardAvailable() const

Возвращает true если текстовый браузер может двигаться вперед по истории документа с помощью forward ().

[override virtual protected] void QTextBrowser::keyPressEvent(QKeyEvent * ev )

The event ev используется для предоставления следующих клавиатурных сокращений:

Keypress Action
Alt+Left Arrow backward()
Alt+Right Arrow forward()
Alt+Up Arrow home()

[override virtual] QVariant QTextBrowser::loadResource(int type , const QUrl & name )

Реализует: QTextEdit::loadResource (тип int, const QUrl и имя).

Эта функция вызывается при загрузке документа и для каждого изображения в документе. type указывает тип загружаемого ресурса. Если ресурс не может быть загружен, возвращается недопустимый QVariant .

Реализация по умолчанию игнорирует type и пытается найти ресурсы,интерпретируя name как имя файла. Если это не абсолютный путь, он пытается найти файл в путях свойства searchPaths и в том же каталоге, что и текущий источник. В случае успеха результатом является QVariant, в котором хранится QByteArray с содержимым файла.

Если вы переопределите эту функцию, вы сможете вернуть другие типы QVariant . В таблице ниже показано, какие типы вариантов поддерживаются в зависимости от типа ресурса:

QTextBrowser Class

The QTextBrowser class provides a rich text browser with hypertext navigation.

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

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.

This property was introduced in Qt 4.2.

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.

This property was introduced in Qt 4.3.

Access functions:

bool openLinks () const
void setOpenLinks (bool open)

readOnly : bool

This property holds whether the text browser is read-only.

By default, this property is true .

Access functions:

bool isReadOnly () const
void setReadOnly (bool ro)

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 <qt type=detail> , 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 setHtml().

By default, this property contains an empty URL.

Access functions:

QUrl source () const
virtual void setSource (const QUrl &name)

undoRedoEnabled : bool

This property holds whether the text browser supports undo/redo operations.

By default, this property is false .

Access functions:

bool isUndoRedoEnabled () const
void setUndoRedoEnabled (bool enable)

Member Function Documentation

QTextBrowser:: QTextBrowser ( QWidget *parent = Q_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.

This function was introduced in Qt 4.4.

void QTextBrowser:: clearHistory ()

Clears the history of visited documents and disables the forward and backward navigation.

This function was introduced in Qt 4.2.

[virtual protected] bool QTextBrowser:: event ( QEvent *e)

[virtual protected] bool QTextBrowser:: focusNextPrevChild ( bool next)

[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.

This function was introduced in Qt 4.4.

[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.

Note: Signal highlighted is overloaded in this class. To connect to this one using the function pointer syntax, you must specify the signal type in a static cast, as shown in this example:

[signal] void QTextBrowser:: highlighted (const QString &link)

This is an overloaded function.

Convenience signal that allows connecting to a slot that takes just a QString, like for example QStatusBar’s message().

Note: Signal highlighted is overloaded in this class. To connect to this one using the function pointer syntax, you must specify the signal type in a static cast, as shown in this example:

[signal] void QTextBrowser:: historyChanged ()

This signal is emitted when the history changes.

This function was introduced in Qt 4.4.

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

This function was introduced in Qt 4.4.

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

This function was introduced in Qt 4.4.

[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().

This function was introduced in Qt 4.2.

bool QTextBrowser:: isForwardAvailable () const

Returns true if the text browser can go forward in the document history using forward().

This function was introduced in Qt 4.2.

[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()

[virtual] QVariant QTextBrowser:: 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 QVariant::Type
QTextDocument::HtmlResource QString or QByteArray
QTextDocument::ImageResource QImage, QPixmap or QByteArray
QTextDocument::StyleSheetResource QString or QByteArray

[virtual protected] void QTextBrowser:: mouseMoveEvent ( QMouseEvent *e)

[virtual protected] void QTextBrowser:: mousePressEvent ( QMouseEvent *e)

[virtual protected] void QTextBrowser:: mouseReleaseEvent ( QMouseEvent *e)

[virtual protected] void QTextBrowser:: paintEvent ( QPaintEvent *e)

[virtual slot] void QTextBrowser:: reload ()

Reloads the current set 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(), backword() or home() or when the user clicks on links or presses the equivalent key sequences.

© 2017 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.

Читать:
Html5 geolocation provider что это за программа

Похожие статьи