在QTextEdit中一次显示一行

2024-09-27 21:23:41 发布

您现在位置:Python中文网/ 问答频道 /正文

enter code here我试图读取一个文件,并用QEditText显示其行。我的代码对于小文件来说运行良好,因为我使用file.read()将整个文件存储在字符串中。然后将整个字符串传递给QEditText

class MainWindowUi(qtw.QWidget):
    def __init__(self,*args,**kwargs):
        super().__init__(*args,**kwargs)
        
        self.setWindowTitle("Logger")
        self.resize(800,800)
        self.setMaximumWidth(800)
        self.setMinimumHeight(800)
        self.layout=qtw.QGridLayout()
        self.upload_file_button=qtw.QPushButton("Upload")
        
        self.display_result=qtw.QTextEdit()
        self.display_result.setReadOnly(True)
        self.display_result.setAcceptRichText(True)
        

        self.layout.addWidget(self.display_result,0,0,0,3)
        self.layout.addWidget(self.upload_file_button,0,4,1,2)
        
        self.setLayout(self.layout)
        
        self.upload_file_button.clicked.connect(self.open)
        self.show()


     def open(self):
        path = qtw.QFileDialog.getOpenFileName(self, '', '',
                                           'Text files (*.txt *log*)')
        if path[0]:
                file=open(path[0],'r',encoding="utf8")
                self.display_file(file.read())
                file.close()


     def  display_file(self,txt=None):
        if len(txt)>0:
            self.display_result.moveCursor( qtg.QTextCursor.End)
            self.display_result.insertPlainText(txt)
        else:
           pass

但对于大文件,这并不是最佳选择。所以我想一次传递一行到QEditText,这样它一次显示一行并自动滚动到末尾。就像我们使用for line in file: print (line)打印文件行一样 所以我试着这么做

 def open(self):
        path = qtw.QFileDialog.getOpenFileName(self, '', '',
                                           'Text files (*.txt *log*)')
        if path[0]:
                file=open(path[0],'r',encoding="utf8")
                for line in file:
                    self.display_file(line)
                file.close()

但是它没有按照我想要的方式工作。它像前面的代码一样一次性显示整个文件。我没有那么多的新加坡知识;插槽。但QEditText似乎只在Open槽的作业完成时显示值

编辑:我之所以要这样做,是因为我不想在加载整个文件之前冻结UI


Tags: 文件pathselftxtdefdisplaylinebutton

热门问题