How to adapt the size of QWebView to its contents



  • This is pyqt5 code, but it doesn't make much difference with its C++ version. You could also post C++ version here If you like. HtmlEditor should display only a line at first, with the height just enough to hold a line, not bigger, not smaller. As the user inputs more lines, the height of HtmlEditor will get bigger too. I tried to use self.page().mainFrame().contentsSize().height() as follows, it didn't work. I tried to replace self.page().mainFrame().contentsSize().height() with self.fontSize + self.contentsMargins().top() + self.contentsMargins().bottom(). But self.contentsMargins().top() and self.contentsMargins().bottom() are always zero. I don't know why. How to do the trick?

    class HtmlEditor(QWebView):
        def __init__(self, fontSize):
            super().__init__()
            self.fontSize = fontSize
            self.page().setContentEditable(True)
            self.page().contentsChanged.connect(self.sizeChange)
            self.setupFont()
            self.sizeChange()
            
        def setupFont(self):
            self.htmlEditorSettings = self.settings()
            self.htmlEditorSettings.setFontSize(QWebSettings.DefaultFontSize, self.fontSize)
        
        def sizeChange(self):
            docHeight = self.page().mainFrame().contentsSize().height()
            self.setFixedHeight(docHeight)

Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.