PyQt how to perform function BEFORE GUI resize event

627 views Asked by At

In PyQt4, is there a way to suspend resize of a window until a function is completed?

My problem is that I have created a window with a text edit that might contain large amounts of text. Since I switched to working with a grid layout, the text edit gets resized as well, and when there is a lot of text, the application hangs. I tried overriding resizeEvent to clear text edit text at resize but the application still hangs, since it is clearing the text only AFTER resizing.

Other solutions are welcomed as well.

The python code (and a link to the .ui file):

import sys
from PyQt4 import QtGui, uic, QtCore
from PyQt4.QtGui import QDesktopWidget

qtCreatorMainWindowFile = "mainwindow.ui"
Ui_MainWindow, QtBaseClass = uic.loadUiType(qtCreatorMainWindowFile)


class MainWindow(QtBaseClass, Ui_MainWindow):
    def __init__(self):
        QtBaseClass.__init__(self)
        self.setupUi(self)
        # Set window size to 4/5 of the screen dimensions
        sg = QDesktopWidget().screenGeometry()
        self.resize(sg.width()*4/5, sg.height()*4/5)

        self.clearTextBrowserButton.clicked.connect(self.ClearTextBrowsers)

        @staticmethod
        def WriteToTextBrowser(string, text_browser):
            cursor = text_browser.textCursor()
            cursor.movePosition(QtGui.QTextCursor.End)
            cursor.insertText(string)
            text_browser.setTextCursor(cursor)
            text_browser.ensureCursorVisible()

        def ClearTextBrowsers(self):
            self.textBrowser.clear()

        # def resizeEvent(self,event):
            # print "resize"
            # self.ClearTextBrowsers()

app = QtGui.QApplication(sys.argv)
window = MainWindow()
window.show()

for i in range(1,100000):
    window.WriteToTextBrowser("TESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTEST\r\n",window.textBrowser)

sys.exit(app.exec_())

The ui. file: https://www.dropbox.com/s/y3hxp6mjhfpv2hy/mainwindow.ui?dl=0

1

There are 1 answers

0
sas On

I found a workaround that seems to work so far. I added an event filter that catches "Move" or "WindowStateChange" QEvents. These seem to happen before the actual resize (the prior works for clicking and stretching and the latter for maximizing/minimizing). The downside is that simply moving the window clears the text edit, but it is a price I'm willing to pay.

The added code (inside MainWindow):

self.installEventFilter(self)

def eventFilter(self, source, event):
    if (event.type() == QtCore.QEvent.Move or event.type() ==  QtCore.QEvent.WindowStateChange):
        self.file.write(self.textBrowser.toPlainText())
        self.ClearTextBrowsers()
    return QtBaseClass.eventFilter(self, source, event)