How can I make QTextEdit save automatically when I'm done typing? I do not want it to be saved automatically when writing each letter separately. Rather, it is saved after all writing is completed only.
import sys
from PyQt5.QtWidgets import *
class MyMainWindow(QMainWindow):
def __init__(self):
super(MyMainWindow, self).__init__()
layout = QHBoxLayout()
centralWidget = QWidget()
centralWidget.setLayout(layout)
self.setCentralWidget(centralWidget)
self.textedit = QTextEdit()
self.textedit.textChanged.connect(self.save_text)
layout.addWidget(self.textedit)
def save_text(self):
text=self.textedit.toPlainText()
with open('mytextfile.txt', 'w') as f:
f.write(text)
if __name__ == "__main__":
app = QApplication(sys.argv)
form = MyMainWindow()
form.show()
sys.exit(app.exec_())
The trick might be to create a button, once the button is pressed then save the text:
import sys
from PyQt5.QtWidgets import *
class MyMainWindow(QMainWindow):
def __init__(self):
super(MyMainWindow, self).__init__()
layout = QHBoxLayout()
centralWidget = QWidget()
centralWidget.setLayout(layout)
self.setCentralWidget(centralWidget)
self.textedit = QTextEdit()
layout.addWidget(self.textedit)
self.pushbutton = QPushButton()
self.pushbutton.clicked.connect(self.save_text)
layout.addWidget(self.textedit)
def save_text(self):
text=self.textedit.toPlainText()
with open('mytextfile.txt', 'w') as f:
f.write(text)
if __name__ == "__main__":
app = QApplication(sys.argv)
form = MyMainWindow()
form.show()
sys.exit(app.exec_())
Then once you done writing your text, just click the button and it will save your text.
Related
Add My second File In QStackwidget.
After pressing the "close" Button from the second file, I can't able to reopen it.
How to reopen the second file? How to refresh the code?
How to close the second/Subwindow file properly and re-open the same from the first file. or If we close the second file, How to refresh the first file fully.
First File
import sys,os
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from sample_countrypage import Countrypage
class MainPage(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle(" Sample Programme")
self.setGeometry(100,100,1000,600)
self.Ui()
self.show()
def Ui(self):
self.countrywindow = Countrypage()
self.stackitems = QStackedWidget()
self.btn1=QPushButton("Open 2nd File")
self.btn1.setFixedSize(100, 30)
self.btn1.clicked.connect(self.countrypage)
self.left_layout = QVBoxLayout()
self.right_layout = QHBoxLayout()
self.main_layout = QHBoxLayout()
self.left_layout.addWidget(self.btn1)
self.left_layout.addStretch()
self.right_frame = QFrame()
self.right_layout = QHBoxLayout(self.right_frame)
self.main_layout.setSpacing(5)
self.main_layout.setContentsMargins(0,0,0,0)
self.main_layout.addLayout(self.left_layout)
self.main_layout.addWidget(self.right_frame)
self.main_layout.addStretch()
self.stackitems.addWidget(self.countrywindow)
self.right_layout.addWidget(self.stackitems)
widget = QWidget()
widget.setLayout(self.main_layout)
self.setCentralWidget(widget)
def countrypage(self):
self.stackitems.setCurrentWidget(self.countrywindow)
if __name__ == "__main__":
app = QApplication(sys.argv)
mainwindow = MainPage()
app.setStyle("fusion")
mainwindow.show()
sys.exit(app.exec_())
SecondFile
import sys,os
from PyQt5.QtWidgets import *
class Countrypage(QWidget):
def __init__(self):
super().__init__()
self.setWindowTitle("Country Page")
self.btn1 = QPushButton("close")
self.btn1.clicked.connect(lambda : self.close())
self.form_layout = QFormLayout()
self.form_layout.addRow("Country",QLineEdit())
self.form_layout.addRow("continent",QLineEdit())
self.layout_btn = QHBoxLayout()
self.layout_btn.addStretch()
self.layout_btn.addWidget(self.btn1)
self.layout_country = QVBoxLayout()
self.layout_country.addLayout(self.form_layout)
self.layout_country.addLayout(self.layout_btn)
self.layout_country.addStretch()
self.setLayout(self.layout_country)
if __name__=="__main__":
app = QApplication(sys.argv)
countrywin = Countrypage()
countrywin.show()
sys.exit(app.exec_())
If you have hidden it then you have to call show():
def countrypage(self):
self.countrywindow.show()
self.stackitems.setCurrentWidget(self.countrywindow)
Note: It is advisable to avoid the abuse of lambda methods, if they are not strictly necessary then do not use them, in your case using a lambda to invoke the close method is unnecessary so you should use:
self.btn1.clicked.connect(self.close)
In addition, the concept of files only serves to order the project but it does not make sense in the execution of the program since the same logic applies if all the logic is in the same file.
I want to show the results by clicking on the button, but if I press this code, the program will end in two seconds.
And 'pursent.ui' is just a widget that hasn't been set up.
import sys
from PyQt5.QtWidgets import *
from PyQt5 import uic
form_class = uic.loadUiType("pursent.ui")[0]
class MyWindow(QMainWindow, form_class):
def __init__(self):
super().__init__()
self.setupUi(self)
self.pushButton.clicked.connect(self.btneve)
def btneve(self):
self.statusbar.showMessage((int(self.lineEdit_2.text())-int(self.lineEdit.text()))/int(self.lineEdit.text())*100)
if __name__ == "__main__":
app = QApplication(sys.argv)
myWindow = MyWindow()
myWindow.show()
app.exec_()
void QStatusBar::showMessage(const QString &message, int timeout = 0)
Hides the normal status indications and displays the given message for the specified number of milli-seconds (timeout).
import sys
from PyQt5.QtWidgets import *
#from PyQt5 import uic
#form_class = uic.loadUiType("pursent.ui")[0]
class MyWindow(QMainWindow): #, form_class):
def __init__(self):
super().__init__()
# self.setupUi(self)
centralWidget = QWidget()
self.setCentralWidget(centralWidget)
self.lineEdit = QLineEdit()
self.lineEdit_2 = QLineEdit()
self.pushButton = QPushButton('Button')
self.pushButton.clicked.connect(self.btneve)
self.statusbar = self.statusBar() # = StatusBar(self)
grid = QGridLayout(centralWidget)
grid.addWidget(self.lineEdit)
grid.addWidget(self.lineEdit_2)
grid.addWidget(self.pushButton)
def btneve(self):
self.statusbar.showMessage(str( # + str
(int(self.lineEdit_2.text())-int(self.lineEdit.text()))/int(self.lineEdit.text())*100)
)
if __name__ == "__main__":
app = QApplication(sys.argv)
myWindow = MyWindow()
myWindow.show()
app.exec_()
I have two files, one for my main window, which has one image and one button and one for a new window. What I want it to do is that when I push the button from my main window, it lets me load a file and show it in a TextEdit widget in the new window
so here I have the files I'm using:
MainWindow.py
import sys
import os
from PyQt5 import QtWidgets, QtGui
from PyQt5.QtWidgets import QApplication, QWidget
from PyQt5.QtWidgets import QPushButton, QVBoxLayout, QTextEdit, QHBoxLayout, QLabel, QMainWindow, QAction, QFileDialog
class Window(QWidget):
def __init__(self, parent=None):
super(Window, self).__init__(parent)
self.img = QLabel()
self.relleno=QLabel()
self.btn_load = QPushButton('Load')
self.width = 400
self.height = 150
self.init_ui()
def init_ui(self):
self.img.setPixmap(QtGui.QPixmap("someimage.png"))
h_layout = QHBoxLayout()
v_layout = QVBoxLayout()
h_final = QHBoxLayout()
h_layout.addWidget(self.img)
v_layout.addWidget(self.btn_load)
h_final.addLayout(h_layout)
h_final.addLayout(v_layout)
self.btn_load.clicked.connect(self.loadafile)
self.setLayout(h_final)
self.setWindowTitle('This is main window')
self.setGeometry(600,150,self.width,self.height)
self.show()
def loadafile(self):
filename = QFileDialog.getOpenFileName(self, 'Open File', os.getenv('HOME'))
with open(filename[0], 'r') as f:
file_text = f.read()
return file_text
def main():
app = QApplication(sys.argv)
main = Window()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
NewWindow.py
import os
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QTextEdit, QVBoxLayout
from MainWindow import loadafile
info=loadafile()
class SecondWindow(QWidget):
def __init__(self):
super(SecondWindow, self).__init__()
self.text = QTextEdit(self)
self.init_ui()
def init_ui(self):
v_layout = QVBoxLayout()
v_layout.addWidget(self.text)
self.setLayout(v_layout)
self.setText(info)
self.setWindowTitle('Opened Text')
self.show()
app = QApplication(sys.argv)
shower = SecondWindow()
sys.exit(app.exec_())
I think the loadafile does return my file_text variable but I don't know how to open the new window from there. I think I need to use a destructor for main window and then show the new window but I'm not sure of how to do this (This is the first time I try OOP)
A program is not a set of files, especially in OOP a program is the interactions of objects. And the objects interact if they have the same scope, so both windows must be created in one place so that the information from one pass to the other.
On the other hand in Qt there is a fundamental concept that is the signals, this functionality allows to notify the change of a state to another object without a lot of dependency, so in this case I will create a signal that transmits the text to the other object.
NewWindow.py
from PyQt5 import QtWidgets
class SecondWindow(QtWidgets.QWidget):
def __init__(self):
super(SecondWindow, self).__init__()
self.text = QtWidgets.QTextEdit(self)
self.init_ui()
def init_ui(self):
v_layout = QtWidgets.QVBoxLayout(self)
v_layout.addWidget(self.text)
self.setWindowTitle('Opened Text')
self.show()
if __name__ == '__main__':
import sys
app = QtWidgets.QApplication(sys.argv)
shower = SecondWindow()
sys.exit(app.exec_())
MainWindow.py
import os
import sys
from PyQt5 import QtCore, QtGui, QtWidgets
from NewWindow import SecondWindow
class Window(QtWidgets.QWidget):
textChanged = QtCore.pyqtSignal(str)
def __init__(self, parent=None):
super(Window, self).__init__(parent)
self.img =QtWidgets.QLabel()
self.relleno=QtWidgets.QLabel()
self.btn_load = QtWidgets.QPushButton('Load')
self.width = 400
self.height = 150
self.init_ui()
def init_ui(self):
self.img.setPixmap(QtGui.QPixmap("someimage.png"))
h_final = QtWidgets.QHBoxLayout(self)
h_final.addWidget(self.img)
h_final.addWidget(self.btn_load)
self.btn_load.clicked.connect(self.loadafile)
self.setWindowTitle('This is main window')
self.setGeometry(600,150,self.width,self.height)
self.show()
#QtCore.pyqtSlot()
def loadafile(self):
filename, _ = QtWidgets.QFileDialog.getOpenFileName(self, 'Open File', os.getenv('HOME'))
with open(filename, 'r') as f:
file_text = f.read()
self.textChanged.emit(file_text)
def main():
app = QtWidgets.QApplication(sys.argv)
main = Window()
s = SecondWindow()
main.textChanged.connect(s.text.append)
sys.exit(app.exec_())
if __name__ == '__main__':
main()
i write some code in pyqt5 that create a table in main main:
class Ui_MainWindow(object):
def setupUi(self, MainWindow): ...
def retranslateUi(self, MainWindow):...
self.pushButton.setText(_translate("MainWindow", "print"))
self.pushButton.clicked.connect(self.printer)
def printer(self):...
and use this class by:
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
i wanna know how can i print from main page of my program?
This can be done rather easy using QPrinter class.
Below is well-commented example of how to do it.
import sys
from PyQt5 import QtGui, QtWidgets, QtPrintSupport
class App(QtWidgets.QMainWindow):
def __init__(self):
super().__init__()
# Create some widgets
self.setGeometry(500, 500, 300, 300)
self.button = QtWidgets.QPushButton(
'Print QTextEdit widget (the one below)', self)
self.button.setGeometry(20, 20, 260, 30)
self.editor = QtWidgets.QTextEdit(
'Wow such text why not change me?', self)
self.editor.setGeometry(20, 60, 260, 200)
self.button.clicked.connect(self.print_widget)
def print_widget(self):
# Create printer
printer = QtPrintSupport.QPrinter()
# Create painter
painter = QtGui.QPainter()
# Start painter
painter.begin(printer)
# Grab a widget you want to print
screen = self.editor.grab()
# Draw grabbed pixmap
painter.drawPixmap(10, 10, screen)
# End painting
painter.end()
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
gui = App()
gui.show()
app.exec_()
To print whole window just replace screen = self.editor.grab() with screen = self.grab()
After a QDialog is shown using either show() or exec_() I need to add some additional widgets dynamically. How can I do this?
Just call show() on your widgets:
#!/usr/bin/env python
#-*- coding:utf-8 -*-
import sip
sip.setapi('QString', 2)
sip.setapi('QVariant', 2)
from PyQt4.QtCore import *
from PyQt4.QtGui import *
class testDialogs(QWidget):
def __init__(self, parent=None):
super(testDialogs, self).__init__(parent)
self.verticalLayout = QVBoxLayout(self)
self.pushButton = QPushButton(self)
self.pushButton.setText("Open a Dialog")
self.pushButton1 = QPushButton(self)
self.pushButton1.setText("Add a Text Edit")
self.plainTextEdit = QPlainTextEdit(self)
self.plainTextEdit.appendPlainText("This is a Widget")
self.verticalLayout.addWidget(self.pushButton)
self.verticalLayout.addWidget(self.pushButton1)
self.verticalLayout.addWidget(self.plainTextEdit)
self.pushButton.clicked.connect(self.on_pushButton_clicked)
self.pushButton1.clicked.connect(self.on_pushButton1_clicked)
#pyqtSlot()
def on_pushButton_clicked(self):
dialog = QDialog(self)
verticalLayout = QVBoxLayout(dialog)
plainTextEdit = QPlainTextEdit(dialog)
plainTextEdit.appendPlainText("This is a Dialog")
buttonBox = QDialogButtonBox(dialog)
buttonBox.setOrientation(Qt.Horizontal)
buttonBox.setStandardButtons(QDialogButtonBox.Cancel|QDialogButtonBox.Ok)
buttonBox.setObjectName("buttonBox")
verticalLayout.addWidget(plainTextEdit)
verticalLayout.addWidget(buttonBox)
buttonBox.accepted.connect(dialog.close)
buttonBox.rejected.connect(dialog.close)
dialog.show()
#pyqtSlot()
def on_pushButton1_clicked(self):
plainTextEdit = QPlainTextEdit(self)
plainTextEdit.appendPlainText("This is another Text Edit")
self.verticalLayout.addWidget(plainTextEdit)
plainTextEdit.show()
if __name__ == "__main__":
import sys
app = QApplication(sys.argv)
main = testDialogs()
main.show()
sys.exit(app.exec_())