QTextEdit的QTextDocument在SetText之后无法调整页面大小

时间:2019-05-08 23:24:18

标签: python qtextedit pyside2

免责声明:我正在使用PySide2;但是,Qt(pyqt5Qt c ++)中的任何答案都可以。

我在设置textedit中的文档大小时遇到​​问题。

当我使用QTextEdit初始化setText(text:QString)时,QTextEdit的{​​{1}}的大小调整行为发生了变化。除非文本在窗口小部件的视口出血,否则将忽略随后应用QTextDocument的情况。

如果最初我没有setPageSize,则无论我是否调整窗口大小,都正确考虑了文档大小。

下面是我所经历的奇怪行为的一个最小示例。如果运行代码,请尝试调整窗口大小,当文本超出窗口小部件时,将考虑到pageSize;但是,如果不是,则setText的pageSize将与其宽度匹配,并且其高度为-1。

如果您关闭QTextEdit,那么一开始就没有问题。如果有任何解释或解决方法,我想听听。

SET_TEXT_TEST

在这里展示一些图片:

页面大小宽度为〜1000 Wide Window

页面大小宽度为623.0 Window A No Wrap

页面大小宽度为622.0 Window A Wrapped

2 个答案:

答案 0 :(得分:1)

您的setPageSize当然被采纳为QTextDocument()

为了证明这一点,我推翻了resizeEvent()。 返回空,说无。

您可以看到文档大小适合您的页面大小。

您确保一次更改文档大小,但是更改后的尺寸很快就会更改为原始尺寸。

因此,您需要注意更改。

为什么会发生这种变化?

我认为这是因为执行QTextEdit resizeEvent。 如果执行QTextEdit,则会发出documentSizeChanged中的QAbstractTextDocumentLayout信号。

如果您阻塞信号,则QTextEdit调整大小时,您将能够获得所需的结果。对我来说,这段代码仍然存在一些问题,但是我想我可以回答您的问题。是的,文档比QMainWindow长。并且您仅更改了文档大小,因此QTextEdit无法显示所有文本。可能是下一个问题。

import PySide2
from PySide2.QtGui import *
from PySide2.QtWidgets import *
from PySide2.QtCore import *
from PySide2.QtPrintSupport import *

SET_TEXT_TEST = True

#In my environment PySide2 fails. So I searched the solution, I found out the codes.This codes are for my verification.
#import sys,os

# in my Environment this code is necessary
#dirname = os.path.dirname(PySide2.__file__)
#plugin_path = os.path.join(dirname, 'plugins', 'platforms')
#os.environ['QT_QPA_PLATFORM_PLUGIN_PATH'] = plugin_path



class IPageEdit(QTextEdit):
    def __init__(self, parent=None):
        super().__init__(parent)
        # these lines don't seem to do anything
        doc = self.document()
        pageSize = QPageSize(QPageSize.A6).size(QPageSize.Point)
        doc.setPageSize(QPageSize(QPageSize.A6).size(QPageSize.Point))

    def paintEvent(self, event):
        doc = self.document()
        pageSize = QPageSize(QPageSize.A6).size(QPageSize.Point)
        doc.setPageSize(QPageSize(QPageSize.A6).size(QPageSize.Point))

        print('({},{})  ({},{})'.format(
            pageSize.width(),
            pageSize.height(),
            doc.pageSize().width(),
            doc.pageSize().height()))

        painter = QPainter(self.viewport())
        doc.drawContents(painter)
    def resizeEvent(self, event):
        self.document().documentLayout().blockSignals(True)
        return QTextEdit.resizeEvent(self, event)

class IMainWindow(QMainWindow):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.resize(1000, 500)
        self.setContentsMargins(20, 20, 20, 20)

        pageEdit = IPageEdit(self)
        if SET_TEXT_TEST:
            pageEdit.setText('''\
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Velit aliquet sagittis id consectetur purus ut faucibus pulvinar elementum. Metus vulputate eu scelerisque felis imperdiet proin fermentum leo vel. Massa tincidunt nunc pulvinar sapien et ligula ullamcorper malesuada proin. Enim neque volutpat ac tincidunt vitae semper. Leo duis ut diam quam nulla porttitor massa id neque. Cras pulvinar mattis nunc sed blandit libero volutpat. Eleifend quam adipiscing vitae proin sagittis. Nulla facilisi cras fermentum odio eu feugiat pretium nibh. Tellus molestie nunc non blandit massa enim nec dui nunc. Eget nullam non nisi est sit amet. Sed odio morbi quis commodo odio aenean sed. Nibh ipsum consequat nisl vel pretium lectus quam id leo. Adipiscing diam donec adipiscing tristique risus nec. Sit amet consectetur adipiscing elit ut aliquam purus sit. Sed sed risus pretium quam. Elit pellentesque habitant morbi tristique senectus. Turpis egestas sed tempus urna.

Nunc aliquet bibendum enim facilisis gravida neque. Condimentum id venenatis a condimentum vitae sapien pellentesque habitant. Purus sit amet volutpat consequat mauris. Mauris in aliquam sem fringilla ut morbi tincidunt augue interdum. Ultrices mi tempus imperdiet nulla malesuada pellentesque elit. Dolor purus non enim praesent elementum facilisis leo vel. Donec adipiscing tristique risus nec. Non consectetur a erat nam. Fusce id velit ut tortor pretium. Sit amet nulla facilisi morbi tempus iaculis urna. Vel facilisis volutpat est velit egestas. Ac orci phasellus egestas tellus rutrum tellus pellentesque.

Turpis tincidunt id aliquet risus feugiat in ante metus. Nibh ipsum consequat nisl vel pretium lectus quam id leo. Amet luctus venenatis lectus magna fringilla urna. Morbi blandit cursus risus at ultrices mi tempus imperdiet. Sit amet porttitor eget dolor. Nec ultrices dui sapien eget mi. Turpis massa tincidunt dui ut ornare lectus sit. Ac odio tempor orci dapibus. Et netus et malesuada fames ac turpis egestas integer. Morbi quis commodo odio aenean. Vulputate sapien nec sagittis aliquam malesuada. Lobortis mattis aliquam faucibus purus in. Sem fringilla ut morbi tincidunt. Volutpat commodo sed egestas egestas fringilla phasellus faucibus.

Tempor orci dapibus ultrices in iaculis nunc sed augue. Etiam sit amet nisl purus in mollis nunc sed. Nulla porttitor massa id neque aliquam vestibulum morbi. Nibh tortor id aliquet lectus proin. Venenatis urna cursus eget nunc scelerisque viverra mauris in. Volutpat odio facilisis mauris sit. Magna eget est lorem ipsum dolor sit amet consectetur. Lacinia quis vel eros donec ac odio tempor. Justo donec enim diam vulputate. Fringilla urna porttitor rhoncus dolor purus. In dictum non consectetur a erat nam at. Egestas erat imperdiet sed euismod nisi porta lorem. Scelerisque fermentum dui faucibus in ornare quam viverra orci. Lectus proin nibh nisl condimentum id venenatis a. Faucibus pulvinar elementum integer enim neque volutpat ac tincidunt. Habitasse platea dictumst quisque sagittis purus sit amet volutpat consequat. Enim sed faucibus turpis in.

Eu lobortis elementum nibh tellus molestie nunc non blandit. Dui id ornare arcu odio. Sit amet nisl purus in mollis nunc sed id semper. Senectus et netus et malesuada fames. Porttitor rhoncus dolor purus non enim praesent elementum. Amet est placerat in egestas erat imperdiet sed euismod. Mi tempus imperdiet nulla malesuada pellentesque elit eget. Tellus molestie nunc non blandit massa enim nec. Pellentesque eu tincidunt tortor aliquam nulla. Ut consequat semper viverra nam libero.
''')
        self.setCentralWidget(pageEdit)




if __name__ == '__main__':
    import sys
    #In my environment, error happends from the second execution unless this code.
    try:
        QApplication(sys.argv)
    except Exception as e:
        print("QApplication is already exists")
    wnd = IMainWindow()
    wnd.show()
    sys.exit(QApplication.exec_())

答案 1 :(得分:0)

基于@Heike的响应,解决方案就像添加以下代码行一样简单:

class IPageEdit(QTextEdit):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setLineWrapMode(QTextEdit.FixedPixelWidth)
        ...

这会产生正确的调整大小行为,并且pageSize在调整大小后会保留其值。