简体   繁体   中英

Opening the text file in the textEdit in the pyQt

I have the Qt files for the reading text file to the textEdit by clicking the push button, but when I am converted it to the .py it is not working. I have the following codes: main.cpp:

#include "mainwindow.h"
#include <QApplication>

int main(int argc, char *argv[])
{
  QApplication a(argc, argv);
  MainWindow w;
  w.show();

  return a.exec();
}

mainwindow.ccp:

#include "mainwindow.h"
#include "ui_mainwindow.h"

#include<QFile>
#include<QTextStream>
#include<QMessageBox>

MainWindow::MainWindow(QWidget *parent) :
  QMainWindow(parent),
  ui(new Ui::MainWindow)
{
  ui->setupUi(this);
}

MainWindow::~MainWindow()
{
  delete ui;
}

void MainWindow::on_pushButton_clicked()
{
  QFile file("filename.txt");

  if( !file.open( QIODevice::ReadOnly))
      QMessageBox::information(0, "info", file.errorString());

  QTextStream in( &file );

  ui->textEdit->setText(in.readAll());
}

mainwindow.h:

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
  Q_OBJECT

public:
  explicit MainWindow(QWidget *parent = 0);
  ~MainWindow();

private slots:
  void on_pushButton_clicked();

private:
  Ui::MainWindow *ui;
};

#endif // MAINWINDOW_H

And I have converted .py file which is not working as above is working well, please suggest me proper correction in below code. mainwindow.py:

from PyQt4 import QtCore, QtGui

try:
  _fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
  _fromUtf8 = lambda s: s

class Ui_MainWindow(object):
  def setupUi(self, MainWindow):
    MainWindow.setObjectName(_fromUtf8("MainWindow"))
    MainWindow.resize(810, 424)
    self.centralWidget = QtGui.QWidget(MainWindow)
    self.centralWidget.setObjectName(_fromUtf8("centralWidget"))
    self.pushButton = QtGui.QPushButton(self.centralWidget)
    self.pushButton.setGeometry(QtCore.QRect(340, 0, 111, 27))
    self.pushButton.setObjectName(_fromUtf8("pushButton"))
    self.scrollArea = QtGui.QScrollArea(self.centralWidget)
    self.scrollArea.setGeometry(QtCore.QRect(10, 30, 791, 331))
    self.scrollArea.setWidgetResizable(True)
    self.scrollArea.setObjectName(_fromUtf8("scrollArea"))
    self.scrollAreaWidgetContents = QtGui.QWidget()
    self.scrollAreaWidgetContents.setGeometry(QtCore.QRect(0, 0, 787, 327))
    self.scrollAreaWidgetContents.setObjectName(_fromUtf8("scrollAreaWidgetContents"))
    self.textEdit = QtGui.QTextEdit(self.scrollAreaWidgetContents)
    self.textEdit.setGeometry(QtCore.QRect(0, 0, 791, 331))
    self.textEdit.setObjectName(_fromUtf8("textEdit"))
    self.scrollArea.setWidget(self.scrollAreaWidgetContents)
    MainWindow.setCentralWidget(self.centralWidget)
    self.menuBar = QtGui.QMenuBar(MainWindow)
    self.menuBar.setGeometry(QtCore.QRect(0, 0, 810, 23))
    self.menuBar.setObjectName(_fromUtf8("menuBar"))
    MainWindow.setMenuBar(self.menuBar)
    self.mainToolBar = QtGui.QToolBar(MainWindow)
    self.mainToolBar.setObjectName(_fromUtf8("mainToolBar"))
    MainWindow.addToolBar(QtCore.Qt.TopToolBarArea, self.mainToolBar)
    self.statusBar = QtGui.QStatusBar(MainWindow)
    self.statusBar.setObjectName(_fromUtf8("statusBar"))
    MainWindow.setStatusBar(self.statusBar)

    self.retranslateUi(MainWindow)
    QtCore.QMetaObject.connectSlotsByName(MainWindow)

  def retranslateUi(self, MainWindow):
    MainWindow.setWindowTitle(QtGui.QApplication.translate("MainWindow", "MainWindow", None, QtGui.QApplication.UnicodeUTF8))
    self.pushButton.setText(QtGui.QApplication.translate("MainWindow", "Open Text", None, QtGui.QApplication.UnicodeUTF8))


if __name__ == "__main__":
  import sys
  app = QtGui.QApplication(sys.argv)
  MainWindow = QtGui.QMainWindow()
  ui = Ui_MainWindow()
  ui.setupUi(MainWindow)
  MainWindow.show()
  sys.exit(app.exec_())

You can do it like:

textEdit = QPlainTextEdit()
text=open('file.txt').read()
textEdit.setPlainText(text)

Or in your code:

text=open('file.txt').read()
self.textEdit.setText(text)

You can also find a simple text editor in PyQt here .

Below is a python port of your C++ code. I have changed a few of the variable names, but it is otherwise functionally exactly the same. It should be saved in the same directory as the mainwindow.py module.

from PyQt4 import QtCore, QtGui
from mainwindow import Ui_MainWindow

class MainWindow(QtGui.QMainWindow):
    def __init__(self, parent=None):
        QtGui.QMainWindow.__init__(self, parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

    @QtCore.pyqtSlot()
    def on_pushButton_clicked(self):
        file = QtCore.QFile('filename.txt')
        if not file.open(QtCore.QIODevice.ReadOnly):
            QtGui.QMessageBox.information(None, 'info', file.errorString())
        stream = QtCore.QTextStream(file)
        self.ui.textEdit.setText(stream.readAll())

if __name__ == '__main__':

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

PS :

There is one small curiosity here. When automatically connecting slots by name , it may be necessary to use the pyqtSlot decorator to distinguish between different overloads of a signal. This situation also occurs with signals (such as clicked ) which have default arguments, because PyQt implements these as separate overloads (one which sends the default, and one which sends nothing). If the decorator wasn't used, both overloads would get connected, and the slot would get called twice.

One final point: it is generally not necessary to run pyuic with the -x or --execute flag. The following is sufficient:

    pyuic4 -o mainwindow.py mainwindow.ui

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM