I have problem with connecting two functions to each other in my small program.
I am using PyQt5 and PyPDF2 modules.I would like to link two pdf files into one.
In my program I have 3 buttons:
btnPlik1 - browse 1st file (connected to function openFile1)
btnPlik2 - browse 2nd file (connected to function openFile2)
btnPlik3 - 'start' - run program (connected to function laczeniePdf)
Functions work separately but when I would like to connect them by clicking 'Start'(btnPlik3) my program crashes. Below is my code:
def openFile1(self):
pathFileName, _ = QtWidgets.QFileDialog.getOpenFileName(None, 'Wybierz plik', '', 'pdf(*.pdf)')
print("PathFileName-'{}', \n_-'{}'".format(pathFileName, _))
if pathFileName:
print("Wybrany plik: ", pathFileName)
g = open(pathFileName, 'rb')
return g
def openFile2(self):
pathFileName, _ = QtWidgets.QFileDialog.getOpenFileName(None, 'Wybierz plik', '', 'pdf(*.pdf)')
print("PathFileName-'{}', \n_-'{}'".format(pathFileName, _))
if pathFileName:
print("Wybrany plik: ", pathFileName)
h = open(pathFileName, 'rb')
return h
def laczeniePdf(self,g, h):
readerLinkPage1 = PyPDF2.PdfFileReader(open(g, 'rb'))
readerLinkPage2 = PyPDF2.PdfFileReader(open(h, 'rb'))
writerLinkPage = PyPDF2.PdfFileWriter()
OutputFile = open('FinalOutput.pdf', 'wb')
writerLinkPage.appendPagesFromReader(readerLinkPage1)
writerLinkPage.appendPagesFromReader(readerLinkPage2)
writerLinkPage.write(OutputFile)
OutputFile.close()
I am looking forward for your hints and advises
EDIT:
Here is code of class we are talking about(it is separate window in my program)
class Ui_PolaczPliki(object):
def setupUi(self, PolaczPliki):
PolaczPliki.setObjectName("PolaczPliki")
PolaczPliki.resize(295, 113)
self.btnPlik1 = QtWidgets.QPushButton(PolaczPliki)
self.btnPlik1.setGeometry(QtCore.QRect(30, 40, 91, 41))
self.btnPlik1.setObjectName("btnPlik1")
self.btnPlik1.clicked.connect(self.openFile1)
self.btnPlik2 = QtWidgets.QPushButton(PolaczPliki)
self.btnPlik2.setGeometry(QtCore.QRect(160, 40, 91, 41))
self.btnPlik2.setObjectName("btnPlik2")
self.btnPlik2.clicked.connect(self.openFile2)
self.btnPlik3 = QtWidgets.QPushButton(PolaczPliki)
self.btnPlik3.setGeometry(QtCore.QRect(80, 80, 40, 20))
self.btnPlik3.setObjectName("btnPlik3")
self.btnPlik3.clicked.connect(self.laczeniePdf)
self.label = QtWidgets.QLabel(PolaczPliki)
self.label.setGeometry(QtCore.QRect(50, 10, 47, 13))
self.label.setObjectName("label")
self.label_2 = QtWidgets.QLabel(PolaczPliki)
self.label_2.setGeometry(QtCore.QRect(180, 10, 47, 13))
self.label_2.setObjectName("label_2")
self.retranslateUi(PolaczPliki)
QtCore.QMetaObject.connectSlotsByName(PolaczPliki)
def retranslateUi(self, PolaczPliki):
_translate = QtCore.QCoreApplication.translate
PolaczPliki.setWindowTitle(_translate("PolaczPliki", "Polacz pliki"))
self.btnPlik1.setText(_translate("PolaczPliki", "Dodaj"))
self.btnPlik2.setText(_translate("PolaczPliki", "Dodaj"))
self.btnPlik3.setText(_translate("PolaczPliki", "Start"))
self.label.setText(_translate("PolaczPliki", "Plik nr 1"))
self.label_2.setText(_translate("PolaczPliki", "Plik nr 2"))
def openFile1(self):
pathFileName, _ = QtWidgets.QFileDialog.getOpenFileName(None, 'Wybierz plik', '', 'pdf(*.pdf)')
print("PathFileName-'{}', \n_-'{}'".format(pathFileName, _))
if pathFileName:
print("Wybrany plik: ", pathFileName)
g = open(pathFileName, 'rb')
return g
def openFile2(self):
pathFileName, _ = QtWidgets.QFileDialog.getOpenFileName(None, 'Wybierz plik', '', 'pdf(*.pdf)')
print("PathFileName-'{}', \n_-'{}'".format(pathFileName, _))
if pathFileName:
print("Wybrany plik: ", pathFileName)
h = open(pathFileName, 'rb')
return h
def laczeniePdf(self, g,h):
readerLinkPage1 = PyPDF2.PdfFileReader(g)
readerLinkPage2 = PyPDF2.PdfFileReader(h)
writerLinkPage = PyPDF2.PdfFileWriter()
OutputFile = open('FinalOutput.pdf', 'wb')
writerLinkPage.appendPagesFromReader(readerLinkPage1)
writerLinkPage.appendPagesFromReader(readerLinkPage2)
writerLinkPage.write(OutputFile)
OutputFile.close()
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
ex = Ui_MainWindow()
w = QtWidgets.QMainWindow()
ex.setupUi(w)
w.show()
sys.exit(app.exec_())
Try it:
import sys
from PyQt5 import QtCore, QtGui, QtWidgets
import PyPDF2
class Ui_PolaczPliki(object):
def __init__(self): # +++
self.file_1 = None # +++
self.file_2 = None # +++
def setupUi(self, PolaczPliki):
PolaczPliki.setObjectName("PolaczPliki")
PolaczPliki.resize(600, 150)
self.btnPlik1 = QtWidgets.QPushButton(PolaczPliki)
self.btnPlik1.setGeometry(QtCore.QRect(30, 40, 91, 41))
self.btnPlik1.setObjectName("btnPlik1")
self.btnPlik1.clicked.connect(self.openFile1)
self.btnPlik2 = QtWidgets.QPushButton(PolaczPliki)
self.btnPlik2.setGeometry(QtCore.QRect(300, 40, 91, 41))
self.btnPlik2.setObjectName("btnPlik2")
self.btnPlik2.clicked.connect(self.openFile2)
self.btnPlik3 = QtWidgets.QPushButton(PolaczPliki)
self.btnPlik3.setGeometry(QtCore.QRect(165, 90, 91, 41))
self.btnPlik3.setObjectName("btnPlik3")
self.btnPlik3.clicked.connect(lambda: self.laczeniePdf(self.file_1, self.file_2)) # +++
self.label = QtWidgets.QLabel(PolaczPliki)
self.label.setGeometry(QtCore.QRect(30, 10, 47, 13))
self.label.setObjectName("label")
self.label_2 = QtWidgets.QLabel(PolaczPliki)
self.label_2.setGeometry(QtCore.QRect(300, 10, 47, 13))
self.label_2.setObjectName("label_2")
self.retranslateUi(PolaczPliki)
QtCore.QMetaObject.connectSlotsByName(PolaczPliki)
def retranslateUi(self, PolaczPliki):
_translate = QtCore.QCoreApplication.translate
PolaczPliki.setWindowTitle(_translate("PolaczPliki", "Polacz pliki"))
self.btnPlik1.setText(_translate("PolaczPliki", "Dodaj Plik nr 1"))
self.btnPlik2.setText(_translate("PolaczPliki", "Dodaj Plik nr 2"))
self.btnPlik3.setText(_translate("PolaczPliki", "Start"))
self.label.setText(_translate("PolaczPliki", "Plik nr 1"))
self.label_2.setText(_translate("PolaczPliki", "Plik nr 2"))
def openFile1(self):
pathFileName, _ = QtWidgets.QFileDialog.getOpenFileName(None, 'Wybierz plik', '', 'pdf(*.pdf)')
print("PathFileName-'{}', \n_-'{}'".format(pathFileName, _))
if pathFileName:
print("\nWybrany plik: ", pathFileName)
self.file_1 = pathFileName # +++
self.label.setText("{}".format(self.file_1)) # +++
self.label.adjustSize() # +++
#g = open(pathFileName, 'rb')
#print("\ng = open(pathFileName, 'rb') =`{}`, \ntype g =`{}` ".format(g, type(g)))
#return g
def openFile2(self):
pathFileName, _ = QtWidgets.QFileDialog.getOpenFileName(None, 'Wybierz plik', '', 'pdf(*.pdf)')
print("PathFileName-'{}', \n_-'{}'".format(pathFileName, _))
if pathFileName:
print("\nWybrany plik: ", pathFileName)
self.file_2 = pathFileName # +++
self.label_2.setText("{}".format(self.file_2)) # +++
self.label_2.adjustSize() # +++
#h = open(pathFileName, 'rb')
#print("\nh = open(pathFileName, 'rb') =`{}`, \ntype h =`{}` ".format(h, type(h)))
#return h
def laczeniePdf(self, file_1, file_2): # +++
g = open(file_1, 'rb') # +++
h = open(file_2, 'rb') # +++
readerLinkPage1 = PyPDF2.PdfFileReader(g)
readerLinkPage2 = PyPDF2.PdfFileReader(h)
writerLinkPage = PyPDF2.PdfFileWriter()
OutputFile = open('FinalOutput.pdf', 'wb')
writerLinkPage.appendPagesFromReader(readerLinkPage1)
writerLinkPage.appendPagesFromReader(readerLinkPage2)
writerLinkPage.write(OutputFile)
OutputFile.close()
print("\n g=`{}` + h=`{}` !!!".format(file_1, file_2))
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
ex = Ui_PolaczPliki() #Ui_MainWindow() # +++
w = QtWidgets.QMainWindow()
ex.setupUi(w)
w.show()
sys.exit(app.exec_())
Related
I'm new to pyqt and trying to make a degrees converter application. Now I want to make the text resizable, when I resize MainWindow.
The code:
from PyQt6 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(QtWidgets.QMainWindow):
def resizeEvent(self, event):
print("Window has been resized")
QtWidgets.QMainWindow.resizeEvent(self, event)
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(305, 250)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Policy.Preferred, QtWidgets.QSizePolicy.Policy.Preferred)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(MainWindow.sizePolicy().hasHeightForWidth())
MainWindow.setSizePolicy(sizePolicy)
MainWindow.setMinimumSize(QtCore.QSize(305, 250))
icon = QtGui.QIcon()
icon.addPixmap(QtGui.QPixmap("../../../../Users/Midgetfucker/Downloads/temperature.png"), QtGui.QIcon.Mode.Normal, QtGui.QIcon.State.Off)
MainWindow.setWindowIcon(icon)
MainWindow.setAutoFillBackground(False)
MainWindow.setDocumentMode(False)
self.centralwidget = QtWidgets.QWidget(parent=MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.gridLayout_3 = QtWidgets.QGridLayout(self.centralwidget)
self.gridLayout_3.setObjectName("gridLayout_3")
self.lineEdit_input = QtWidgets.QLineEdit(parent=self.centralwidget)
self.lineEdit_input.setStyleSheet("")
self.lineEdit_input.setLocale(QtCore.QLocale(QtCore.QLocale.Language.Russian, QtCore.QLocale.Country.Russia))
self.lineEdit_input.setObjectName("lineEdit_input")
self.gridLayout_3.addWidget(self.lineEdit_input, 0, 1, 1, 1)
self.label_fahrenheit = QtWidgets.QLabel(parent=self.centralwidget)
font = QtGui.QFont()
font.setPointSize(8)
font.setBold(True)
font.setWeight(75)
self.label_fahrenheit.setFont(font)
self.label_fahrenheit.setObjectName("label_fahrenheit")
self.gridLayout_3.addWidget(self.label_fahrenheit, 0, 0, 1, 1)
self.plainTextEdit_output = QtWidgets.QPlainTextEdit(parent=self.centralwidget)
self.plainTextEdit_output.viewport().setProperty("cursor", QtGui.QCursor(QtCore.Qt.CursorShape.ArrowCursor))
self.plainTextEdit_output.setFocusPolicy(QtCore.Qt.FocusPolicy.NoFocus)
self.plainTextEdit_output.setObjectName("plainTextEdit_output")
self.gridLayout_3.addWidget(self.plainTextEdit_output, 1, 0, 1, 2)
MainWindow.setCentralWidget(self.centralwidget)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
self.add_functions()
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "Преобразователь температур"))
self.label_fahrenheit.setText(_translate("MainWindow", "Градусы:"))
def add_functions(self):
self.lineEdit_input.textChanged.connect(self.degrees_changed)
def degrees_changed(self):
self.plainTextEdit_output.setPlainText("")
self.plainTextEdit_output.setStyleSheet("")
degrees = self.lineEdit_input.text()
if degrees == '':
return
degrees = degrees.replace(',', '.')
try:
degrees = float(degrees)
except ValueError:
self.plainTextEdit_output.setPlainText("Некорректный ввод")
self.plainTextEdit_output.setStyleSheet("color: rgb(255, 0, 0);")
self.lineEdit_input.setFocus()
return
f_to_c = round((degrees * 9/5 + 32), 2)
f_to_k = round((degrees - 32) * 5/9 + 273.15, 2)
c_to_f = round((degrees - 32) * 5/9, 2)
c_to_k = round(degrees + 273.15, 2)
k_to_f = round((degrees - 273.15) * 9/5 + 32, 2)
k_to_c = round(degrees - 273.15, 2)
if round(f_to_c) == f_to_c:
f_to_c = int(f_to_c)
if round(f_to_k) == f_to_k:
f_to_k = int(f_to_k)
if round(c_to_f) == c_to_f:
c_to_f = int(c_to_f)
if round(c_to_k) == c_to_k:
c_to_k = int(c_to_k)
if round(k_to_f) == k_to_f:
k_to_f = int(k_to_f)
if round(k_to_c) == k_to_c:
k_to_c = int(k_to_c)
if round(degrees) == degrees:
degrees = int(degrees)
f_to_c = str(f_to_c)
f_to_k = str(f_to_k)
c_to_f = str(c_to_f)
c_to_k = str(c_to_k)
k_to_c = str(k_to_c)
k_to_f = str(k_to_f)
degrees = str(degrees)
self.plainTextEdit_output.setPlainText('°F: \n'
+ degrees + '°F = ' + f_to_c + '°C' + '\n'
+ degrees + '°F = ' + f_to_k + '°K' + '\n\n'
+ '°C: \n'
+ degrees + '°C = ' + c_to_f + '°F' + '\n'
+ degrees + '°C = ' + c_to_k + '°K' + '\n\n'
+ '°K: \n'
+ degrees + '°K = ' + k_to_f + '°F' + '\n'
+ degrees + '°K = ' + k_to_c + '°C')
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec())
I've already tried this, but doesn't work for me. Any hints or ideas pls?
Windows 10
Using Qt Designer with PyCharm
Hi guys I want the user to choose the motor speed before going into step. So, in the first class, I made the first window which asked for the motor speed and another one is the recording and predicting process. In the recording process, I want to collect the WAV file as future data and use the motor speed as a file name. But I cannot pass the self.RPM value from one class to another. This is some part of the code.
class Ui_Form(object):
def setupUi(self, Form):
#The rest of the code
def retranslateUi(self, Form):
#The rest of the code
def start_click(self):
print('Start button click')
_translate = QtCore.QCoreApplication.translate
self.label.setText(_translate("Form", "<html><head/><body><p align=\"center\"><span style=\" color:#000000;\">Recording</span></p></body></html>"))
app.processEvents()
time.sleep(1)
count = 0
round = 0
for i in range(3):
round = i + 1
text = "Round " + str(round) + "/3"
self.label.setText(text)
app.processEvents()
print(text)
#Recording
now = datetime.now()
day = now.strftime("%d")
month = now.strftime("%m")
year = now.strftime("%y")
hour = now.strftime("%H")
minute = now.strftime("%M")
second = now.strftime("%S")
print(day,"/",month,"/",year,hour,":",minute,":",second)
CHUNK = 1024 #The number of frames in the buffer
FORMAT = pyaudio.paInt16
CHANNELS = 1 #Each frame will have 2 samples
RATE = 44100 #The number of samples collected per second or we can called sample rate
RECORD_SECONDS = 2 #Duration of recording
WAVE_OUTPUT_FILENAME = f"Data2/Test/{day}{month}{year}_{hour}{minute}{second}.wav" <--- I want to add RPM value here
p = pyaudio.PyAudio()
stream = p.open(format = FORMAT, channels = CHANNELS, rate = RATE, input = True, frames_per_buffer = CHUNK)
print("* recording")
frames = []
for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):
data = stream.read(CHUNK) #read audio data from the stream
frames.append(data)
print("* done recording")
self.label.setText(_translate("Form", "<html><head/><body><p align=\"center\"><span style=\" color:#000000;\">Done Recording</span></p></body></html>"))
stream.stop_stream()
stream.close()
p.terminate()
wf = wave.open(WAVE_OUTPUT_FILENAME, 'wb') # 'rb' read only, 'wb' write only
wf.setnchannels(CHANNELS)
wf.setsampwidth(p.get_sample_size(FORMAT))
wf.setframerate(RATE)
wf.writeframes(b''.join(frames)) #
wf.close()
#The rest of the code
class Ui_Form2(object):
def openWindow(self):
self.window = QtWidgets.QWidget()
self.ui = Ui_Form()
self.ui.setupUi(self.window)
self.window.show()
def setupUi(self, Form):
Form.setObjectName("Form")
Form.resize(422, 202)
Form.setFixedSize(422, 202)
self.pushButton = QtWidgets.QPushButton(Form, clicked = lambda: self.openWindow())
self.pushButton.setGeometry(QtCore.QRect(10, 120, 121, 71))
font = QtGui.QFont()
font.setPointSize(15)
self.pushButton.setFont(font)
self.pushButton.setObjectName("pushButton")
self.pushButton_2 = QtWidgets.QPushButton(Form, clicked = lambda: self.openWindow())
self.pushButton_2.setGeometry(QtCore.QRect(150, 120, 121, 71))
font = QtGui.QFont()
font.setPointSize(15)
self.pushButton_2.setFont(font)
self.pushButton_2.setObjectName("pushButton_2")
self.pushButton_3 = QtWidgets.QPushButton(Form, clicked = lambda: self.openWindow())
self.pushButton_3.setGeometry(QtCore.QRect(290, 120, 121, 71))
font = QtGui.QFont()
font.setPointSize(15)
self.pushButton_3.setFont(font)
self.pushButton_3.setObjectName("pushButton_3")
self.label = QtWidgets.QLabel(Form)
self.label.setGeometry(QtCore.QRect(70, 20, 281, 81))
self.label.setFrameShape(QtWidgets.QFrame.WinPanel)
self.label.setFrameShadow(QtWidgets.QFrame.Sunken)
self.label.setObjectName("label")
self.retranslateUi(Form)
QtCore.QMetaObject.connectSlotsByName(Form)
def retranslateUi(self, Form):
_translate = QtCore.QCoreApplication.translate
Form.setWindowTitle(_translate("Form", "Form"))
self.pushButton.setText(_translate("Form", "1300 RPM"))
self.pushButton.clicked.connect(lambda: self.rpm_button_clicked(self.pushButton.text()))
self.pushButton_2.setText(_translate("Form", "1500 RPM"))
self.pushButton_2.clicked.connect(lambda: self.rpm_button_clicked(self.pushButton_2.text()))
self.pushButton_3.setText(_translate("Form", "1800 RPM"))
self.pushButton_3.clicked.connect(lambda: self.rpm_button_clicked(self.pushButton_3.text()))
self.label.setText(_translate("Form", "<html><head/><body><p align=\"center\"><span style=\" font-size:18pt; font-weight:600;\">RPM Selection</span></p></body></html>"))
def rpm_button_clicked(self, button_text):
rpm_values = {'1300 RPM': 1300, '1500 RPM': 1500, '1800 RPM': 1800}
self.RPM = rpm_values[button_text]
print(self.RPM)
if __name__ == "__main__":
Form = QtWidgets.QWidget()
ui = Ui_Form2()
ui.setupUi(Form)
Form.show()
sys.exit(app.exec_())
I want to use the value from one class on another or anyone got a better idea than this can suggest
Either you use signal/slots (a Qt mechanism for observer/observable), or do it the Python object way.
Signal and slot
In the first case, you need to declare a signal in the class (A) where you select the motor speed, then in your other class (B) you connect the signal for your instance of A to a slot in your B instance.
When doing Qt graphical applications, I prefer to use toy examples to better understand how it works.
Here is what I mean :
import sys
from typing import Optional
from PyQt5 import QtWidgets, QtCore
class WindowA(QtWidgets.QMainWindow):
def __init__(self):
super().__init__(parent=None)
self.setWindowTitle("A")
central_widget = QtWidgets.QPushButton("Choose")
central_widget.clicked.connect(self.on_button_Choose_pushed)
self.setCentralWidget(central_widget)
def on_button_Choose_pushed(self, checked: bool) -> None:
print("'choose' button clicked")
file_dialog = QtWidgets.QFileDialog(parent=self)
if file_dialog.exec():
print("a file was selected")
filenames = file_dialog.selectedFiles()
print(filenames)
assert len(filenames) == 1
print("emitting the signal")
self.file_selected.emit(filenames[0])
else:
print("no file selected")
file_selected = QtCore.pyqtSignal(str)
class WindowB(QtWidgets.QMainWindow):
def __init__(self, window_a: WindowA):
super().__init__(parent=None)
self.setWindowTitle("B")
self.filename: Optional[str] = None
central_widget = QtWidgets.QPushButton("Do something")
central_widget.clicked.connect(self.on_button_Do_Something_pushed)
self.setCentralWidget(central_widget)
window_a.file_selected.connect(self.on_file_selected)
def on_button_Do_Something_pushed(self, checked: bool) -> None:
print("'do something' button clicked")
print("filename is :", repr(self.filename))
# do something
#QtCore.pyqtSlot(str)
def on_file_selected(self, filename: str) -> None:
print("'file selected' slot received a signal, filename =", repr(filename))
self.filename = filename
def main() -> int:
app = QtWidgets.QApplication([])
window_a = WindowA()
window_a.setVisible(True)
window_b = WindowB(window_a) # passing A to B
window_b.setVisible(True)
return app.exec()
if __name__ == "__main__":
sys.exit(main())
(the 2 windows may appear one on top of the other)
Click the button B "do something" button, then the A button "choose" and select a file, then click B again. You will get :
'do something' button clicked
filename is : None
'choose' button clicked
a file was selected
['/home/stack_overflow/log.log']
emitting the signal
'file selected' slot received a signal, filename = '/home/stack_overflow/log.log'
'do something' button clicked
filename is : '/home/stack_overflow/log.log'
Just objects
This is the over way around. You need your A to know of B, so that when a file is selected from A, it sets the variable for B.
import sys
from typing import Optional
from PyQt5 import QtWidgets, QtCore
class WindowA(QtWidgets.QMainWindow):
def __init__(self, window_b: "WindowB"):
super().__init__(parent=None)
self.setWindowTitle("A")
self._window_b = window_b # save it for later
central_widget = QtWidgets.QPushButton("Choose")
central_widget.clicked.connect(self.on_button_Choose_pushed)
self.setCentralWidget(central_widget)
def on_button_Choose_pushed(self, checked: bool) -> None:
print("'choose' button clicked")
file_dialog = QtWidgets.QFileDialog(parent=self)
if file_dialog.exec():
print("a file was selected")
filenames = file_dialog.selectedFiles()
print(filenames)
assert len(filenames) == 1
print("setting the variable of B")
self._window_b.filename = filenames[0]
else:
print("no file selected")
class WindowB(QtWidgets.QMainWindow):
def __init__(self):
super().__init__(parent=None)
self.setWindowTitle("B")
self.filename: Optional[str] = None
central_widget = QtWidgets.QPushButton("Do something")
central_widget.clicked.connect(self.on_button_Do_Something_pushed)
self.setCentralWidget(central_widget)
def on_button_Do_Something_pushed(self, checked: bool) -> None:
print("'do something' button clicked")
print("filename is :", self.filename)
# do something
def main() -> int:
app = QtWidgets.QApplication([])
window_b = WindowB()
window_b.setVisible(True)
window_a = WindowA(window_b) # passing B to A
window_a.setVisible(True)
return app.exec()
if __name__ == "__main__":
sys.exit(main())
This way, A sets the variable of B.
Conclusion
If you understand these 2 techniques, you can change the structure. You can have a class containing the data, and the other being given a reference to the first class.
Or you could make the code that instantiate both of them (here is is the main() function) connect the signal from the first to the slot of the second.
when I added function for a button to show data in CSV file when I click the program, it closes itself. I altered my code, however, the same problem persists.
Debug does not show any error messages. I'm a beginner in qt and if there alternatives to qtablewidget or better ways to tackle this, please let me know.
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'officer.ui'
#
# Created by: PyQt5 UI code generator 5.6
#
# WARNING! All changes made in this file will be lost!
import sys
import csv
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Form(QtWidgets.QWidget):
def setupUi(self, Form):
Form.setObjectName("Form")
Form.resize(930, 650)
self.fname = "data.csv"
self.combo_data2 = {0: ['إيهاب السيد محمود السيد'],
1: ['محمد مدحت محمد', 'محمد عبدالرؤوف متولي', 'وليد عزت عبدالمؤمن', 'هاني حسنين أحمد حسنين',
'محمود السيد سليمان'], 2: ['حازم فتحي مختار', 'أمير محمود سيد', 'أحمد عبدالجليل'],
3: ['ابراهيم مختار عبدالقوي', "أحمد عفيفي محمود عفيفي", 'محمود عبدالعزيز عبدالحميد',
'حسام جابر عبدالعزيز', 'إسلام مصطفى محمد', 'محمد عطيوة عبدالرازق'],
4: ["إسلام عبدالرحمن حسن", "محمد عبدالمنعم محمد يونس", 'محمد فتحي عبدالوهاب',
'محمود عبدالسلام', 'عاصم عادل عبدالعزيز'],
5: ["أحمد محمد عزت", "محمد رضا عبدالعظيم", "أحمد رمضان موسى", "عمر عناني عناني",
"حازم سامي ابراهيم", 'عبدالرحمن سمير ', 'أحمد محمد ابراهيم', 'محمد أحمد عايش',
'سعيد مدحت رأفت', 'أحمد محمد محمود البقري', 'وليد ابراهيم عبدالمجيد',
'محمد عبدالحميد سالم', 'حاتم محمد نجيب'], 6: ["محمود سامي عبدالغفار شعير"]}
self.pushButton = QtWidgets.QPushButton(Form)
self.pushButton.setGeometry(QtCore.QRect(190, 60, 75, 22))
self.pushButton.setObjectName("pushButton")
self.pushButton1 = QtWidgets.QPushButton(Form)
self.pushButton1.setGeometry(QtCore.QRect(50, 110, 85, 22))
self.pushButton1.setObjectName("pushButton1")
self.pushButton2 = QtWidgets.QPushButton(Form)
self.pushButton2.setGeometry(QtCore.QRect(150, 110, 85, 22))
self.pushButton2.setObjectName("pushButton2")
self.tableWidget = QtWidgets.QTableWidget(Form)
self.tableWidget.setEnabled(True)
self.tableWidget.setEditTriggers(QtWidgets.QTableWidget.NoEditTriggers) # Make table not editable
self.tableWidget.setGeometry(QtCore.QRect(25, 151, 881, 471))
self.tableWidget.setObjectName("tableWidget")
self.tableWidget.setColumnCount(4)
self.tableWidget.setRowCount(38)
self.col_headers = ['الرتبة', 'الإسم', 'رصيد سنوية', 'رصيد عارضة']
self.tableWidget.setHorizontalHeaderLabels(self.col_headers)
self.tableWidget.setLayoutDirection(QtCore.Qt.RightToLeft)
header = self.tableWidget.horizontalHeader()
header.setSectionResizeMode(0, QtWidgets.QHeaderView.Stretch)
header.setSectionResizeMode(1, QtWidgets.QHeaderView.ResizeToContents)
header.setSectionResizeMode(2, QtWidgets.QHeaderView.ResizeToContents)
self.comboBox = QtWidgets.QComboBox(Form)
self.comboBox.setGeometry(QtCore.QRect(728, 60, 121, 22))
self.comboBox.setEditable(False)
self.comboBox.setObjectName("comboBox")
self.comboBox.addItem("")
self.comboBox.addItem("")
self.comboBox.addItem("")
self.comboBox.addItem("")
self.comboBox.addItem("")
self.comboBox.addItem("")
self.comboBox.addItem("")
self.comboBox_2 = QtWidgets.QComboBox(Form)
self.comboBox.setLayoutDirection(QtCore.Qt.RightToLeft)
self.comboBox_2.setLayoutDirection(QtCore.Qt.RightToLeft)
self.comboBox_2.setGeometry(QtCore.QRect( 348, 60, 311, 22))
self.comboBox_2.setEditable(False)
self.comboBox_2.setCurrentText("")
self.comboBox_2.setObjectName("comboBox_2")
self.tableWidget.raise_()
self.pushButton.raise_()
self.comboBox.raise_()
self.comboBox_2.raise_()
self.set_combo()
self.comboBox.currentIndexChanged.connect(self.set_combo)
self.pushButton.clicked.connect(self.open_csv)
self.retranslateUi(Form)
self.comboBox.setCurrentIndex(0)
QtCore.QMetaObject.connectSlotsByName(Form)
def open_csv(self):
with open(self.fname , 'r') as record :
for row_data in csv.reader(record):
row = self.tableWidget.rowCount()
self.tableWidget.insertRow(row)
for col , data in enumerate(row_data):
item = QtGui.QTextTableCellFormat(data)
self.tableWidget.setItem( row , col, item)
def search(self):
print 'search'
def set_combo(self):
self.comboBox_2.clear()
x = self.comboBox.currentIndex()
self.comboBox_2.addItems(self.combo_data2[x])
print x
print type(x)
def retranslateUi(self, Form):
_translate = QtCore.QCoreApplication.translate
Form.setWindowTitle(_translate("Form", "بيانات الضباط"))
self.pushButton.setText(_translate("Form", "بحث"))
self.pushButton1.setText(_translate("Form", "خصم عارضة"))
self.pushButton2.setText(_translate("Form", "خصم سنوية"))
self.comboBox.setToolTip(_translate("Form", "<html><head/><body><p>الرتبة</p></body></html>"))
self.comboBox.setCurrentText(_translate("Form", "الرتبة"))
self.comboBox_2.setCurrentText(_translate("Form", "الإسم"))
self.comboBox.setItemText(0, _translate("Form", "عميد"))
self.comboBox.setItemText(1, _translate("Form", "عقيد"))
self.comboBox.setItemText(2, _translate("Form", "مقدم"))
self.comboBox.setItemText(3, _translate("Form", "رائد"))
self.comboBox.setItemText(4, _translate("Form", "نقيب"))
self.comboBox.setItemText(5, _translate("Form", "ملازم أول"))
self.comboBox.setItemText(6, _translate("Form", "ملازم"))
self.comboBox_2.setToolTip(_translate("Form", "<html><head/><body><p>الإسم</p></body></html>"))
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
Form = QtWidgets.QWidget()
ui = Ui_Form()
ui.setupUi(Form)
Form.show()
sys.exit(app.exec_())
I do not understand why you use QTextTableCellFormat, QTableWidget expects a QTableWidgetItem:
def open_csv(self):
self.tableWidget.setRowCount(0)
with open(self.fname , 'r') as record :
for row_data in csv.reader(record):
row = self.tableWidget.rowCount()
self.tableWidget.insertRow(row)
for col , data in enumerate(row_data):
item = QtWidgets.QTableWidgetItem(data)
self.tableWidget.setItem( row , col, item)
I have three main sections of a main window, where the left side (critical data) should take the entire height of the window, while the data on the right should be split between top and bottom. Data in the lower right is related, but not critical - which is why I'd like it to be un-dockable/closable.
The Qt documentation shows an example of this in C++, but I have no idea how to turn this into Python code, as I have no C++ experience.
The Qt Designer application limits the user to Left/Right/Top/Bottom, and limiting the maximum width of the widget doesn't allow me to occupy the un-used space (i.e. doesn't allow the list widget on the left to take up the full height of the main window)
Long story short, to get a Qdockwidget into the lower right corner, you have to put another dock widget above it (it's still limited to Right/Left/Top/Bottom DockWidgetArea). After looking at the answer from eyllanesc below, I'll post two solutions. First, a simplified version of his code and then a modified version of the code I originally posted.
Eyllanesc's translation from the C++ example from I mentioned above:
from PyQt4 import QtCore, QtGui
class MainWindow(QtGui.QMainWindow):
def __init__(self, parent=None):
QtGui.QMainWindow.__init__(self, parent)
self.resize(600, 600)
self.centralWidget = QtGui.QTextEdit()
self.setCentralWidget(self.centralWidget)
# Upper table widget
dock = QtGui.QDockWidget("Upper", self.centralWidget)
dock.setAllowedAreas(QtCore.Qt.RightDockWidgetArea)
self.tableWidget = QtGui.QTableWidget(dock)
self.tableWidget.setObjectName("tableWidget")
self.tableWidget.setColumnCount(6)
self.tableWidget.setRowCount(7)
for i in range(7):
item = QtGui.QTableWidgetItem()
self.tableWidget.setVerticalHeaderItem(i, item)
self.tableWidget.verticalHeaderItem(i).setText("Item " + str(i + 1))
for i in range(6):
item = QtGui.QTableWidgetItem()
self.tableWidget.setHorizontalHeaderItem(i, item)
dock.setWidget(self.tableWidget)
self.addDockWidget(QtCore.Qt.RightDockWidgetArea, dock)
# Lower table widget
dock = QtGui.QDockWidget("Lower", self.centralWidget)
self.tableWidget_2 = QtGui.QTableWidget(dock)
self.tableWidget_2.setObjectName("tableWidget_2")
self.tableWidget_2.setColumnCount(6)
self.tableWidget_2.setRowCount(7)
for i in range(7):
item = QtGui.QTableWidgetItem()
self.tableWidget_2.setVerticalHeaderItem(i, item)
for i in range(6):
item = QtGui.QTableWidgetItem()
self.tableWidget_2.setHorizontalHeaderItem(i, item)
dock.setWidget(self.tableWidget_2);
self.addDockWidget(QtCore.Qt.RightDockWidgetArea, dock)
self.listWidget = QtGui.QListWidget(self.centralWidget)
self.listWidget.setLayoutDirection(QtCore.Qt.RightToLeft)
self.listWidget.setObjectName("listWidget")
for i in range(10):
item = QtGui.QListWidgetItem()
self.listWidget.addItem(item)
item = self.listWidget.item(i)
item.setText("Item " + str(i + 1))
self.listWidget.setMinimumSize(QtCore.QSize(340, 600))
self.setWindowTitle("Dock Widgets")
if __name__ == '__main__':
import sys
app = QtGui.QApplication(sys.argv)
w = MainWindow()
w.show()
sys.exit(app.exec_())
And the modified version of the code I originally used:
from PyQt4 import QtCore, QtGui
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(800, 600)
self.centralwidget = QtGui.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.gridLayout = QtGui.QGridLayout(self.centralwidget)
self.gridLayout.setObjectName("gridLayout")
self.listWidget = QtGui.QListWidget(self.centralwidget)
self.listWidget.setObjectName("listWidget")
self.gridLayout.addWidget(self.listWidget, 0, 0, 1, 1)
self.listWidget.setLayoutDirection(QtCore.Qt.RightToLeft)
for i in range(10):
item = QtGui.QListWidgetItem()
self.listWidget.addItem(item)
item = self.listWidget.item(i)
item.setText("Item " + str(i + 1))
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtGui.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 26))
self.menubar.setObjectName("menubar")
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtGui.QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
self.dockWidget = QtGui.QDockWidget(MainWindow)
self.dockWidget.setFeatures(QtGui.QDockWidget.DockWidgetFloatable)
self.dockWidget.setObjectName("dockWidget")
self.dockWidgetContents = QtGui.QWidget()
self.dockWidgetContents.setObjectName("dockWidgetContents")
self.tableWidget = QtGui.QTableWidget(self.dockWidgetContents)
self.tableWidget.setObjectName("tableWidget")
self.tableWidget.setColumnCount(6)
self.tableWidget.setRowCount(7)
for i in range(7):
item = QtGui.QTableWidgetItem()
self.tableWidget.setVerticalHeaderItem(i, item)
self.tableWidget.verticalHeaderItem(i).setText("Item " + str(i + 1))
for i in range(6):
item = QtGui.QTableWidgetItem()
self.tableWidget.setHorizontalHeaderItem(i, item)
self.gridLayout_2 = QtGui.QGridLayout(self.dockWidgetContents)
self.gridLayout_2.setObjectName("gridLayout_2")
self.gridLayout_2.addWidget(self.tableWidget, 0, 0, 1, 1)
self.dockWidget.setWidget(self.dockWidgetContents)
MainWindow.addDockWidget(QtCore.Qt.DockWidgetArea(2), self.dockWidget)
self.dockWidget_2 = QtGui.QDockWidget(MainWindow)
self.dockWidget_2.setFeatures(QtGui.QDockWidget.DockWidgetClosable|QtGui.QDockWidget.DockWidgetFloatable)
self.dockWidget_2.setObjectName("dockWidget_2")
self.dockWidgetContents_2 = QtGui.QWidget()
self.dockWidgetContents_2.setObjectName("dockWidgetContents_2")
self.gridLayout_3 = QtGui.QGridLayout(self.dockWidgetContents_2)
self.gridLayout_3.setObjectName("gridLayout_3")
self.tableWidget_2 = QtGui.QTableWidget(self.dockWidgetContents)
self.tableWidget_2.setObjectName("tableWidget_2")
self.tableWidget_2.setColumnCount(6)
self.tableWidget_2.setRowCount(7)
for i in range(7):
item = QtGui.QTableWidgetItem()
self.tableWidget_2.setVerticalHeaderItem(i, item)
for i in range(6):
item = QtGui.QTableWidgetItem()
self.tableWidget_2.setHorizontalHeaderItem(i, item)
self.gridLayout_3.addWidget(self.tableWidget_2, 0, 0, 1, 1)
self.dockWidget_2.setWidget(self.dockWidgetContents_2)
MainWindow.addDockWidget(QtCore.Qt.DockWidgetArea(2), self.dockWidget_2)
MainWindow.setWindowTitle("MainWindow")
QtCore.QMetaObject.connectSlotsByName(MainWindow)
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_())## Heading ##
My answer is a translation of this example: http://doc.qt.io/qt-5/qtwidgets-mainwindows-dockwidgets-example.html, so future readers can use it to make a translation from the C++ code to Python.
from PyQt4 import QtCore, QtGui
class MainWindow(QtGui.QMainWindow):
def __init__(self, parent=None):
QtGui.QMainWindow.__init__(self, parent)
self.textEdit = QtGui.QTextEdit()
self.setCentralWidget(self.textEdit)
self.createActions()
self.createStatusBar()
self.createDockWindows()
self.setWindowTitle("Dock Widgets")
self.newLetter()
self.setUnifiedTitleAndToolBarOnMac(True)
def newLetter(self):
self.textEdit.clear()
cursor = QtGui.QTextCursor(self.textEdit.textCursor())
cursor.movePosition(QtGui.QTextCursor.Start)
topFrame = cursor.currentFrame()
topFrameFormat = topFrame.frameFormat()
topFrameFormat.setPadding(16)
topFrame.setFrameFormat(topFrameFormat)
textFormat = QtGui.QTextCharFormat()
boldFormat = QtGui.QTextCharFormat()
boldFormat.setFontWeight(QtGui.QFont.Bold)
italicFormat = QtGui.QTextCharFormat()
italicFormat.setFontItalic(True)
tableFormat = QtGui.QTextTableFormat()
tableFormat.setBorder(1)
tableFormat.setCellPadding(16)
tableFormat.setAlignment(QtCore.Qt.AlignRight)
cursor.insertTable(1, 1, tableFormat)
cursor.insertText("The Firm", boldFormat)
cursor.insertBlock()
cursor.insertText("321 City Street", textFormat)
cursor.insertBlock()
cursor.insertText("Industry Park")
cursor.insertBlock()
cursor.insertText("Some Country")
cursor.setPosition(topFrame.lastPosition())
cursor.insertText(QtCore.QDate.currentDate().toString("d MMMM yyyy"), textFormat)
cursor.insertBlock()
cursor.insertBlock()
cursor.insertText("Dear ", textFormat)
cursor.insertText("NAME", italicFormat)
cursor.insertText(",", textFormat)
for i in range(3):
cursor.insertBlock()
cursor.insertText("Yours sincerely,", textFormat)
for i in range(3):
cursor.insertBlock()
cursor.insertText("The Boss", textFormat)
cursor.insertBlock()
cursor.insertText("ADDRESS", italicFormat)
def print_(self):
document = self.textEdit.document()
printer = QtGui.QPrinter()
dlg = QtGui.QPrintDialog(printer, self)
if dlg.exec() != QtGui.QDialog.Accepted:
return
document.print_(printer)
self.statusBar().showMessage("Ready", 2000)
def save(self):
fileName = QtGui.QFileDialog.getSaveFileName(self,
"Choose a file name", ".", "HTML document (*.html *.htm)")
if not fileName:
return
file = QtCore.QFile(fileName)
if not file.open(QtCore.QFile.WriteOnly | QtCore.QFile.Text):
QtGui.QMessageBox.warning(self, "Dock Widgets",
"Cannot write file {}:\n{}."
.format(QtCore.QDir.toNativeSeparators(fileName), file.errorString()))
return
out = QTextStream(file)
QtGui.QApplication.setOverrideCursor(QtCore.Qt.WaitCursor)
out << textEdit.toHtml()
QtGui.QApplication.restoreOverrideCursor()
self.statusBar().showMessage("Saved '{}'".format(fileName), 2000)
def undo(self):
document = self.textEdit.document()
document.undo()
def insertCustomer(self, customer):
if not customer:
return
customerList = customer.split(", ")
document = self.textEdit.document()
cursor = document.find("NAME")
if not cursor.isNull():
cursor.beginEditBlock()
cursor.insertText(customerList[0])
oldcursor = cursor
cursor = document.find("ADDRESS")
if not cursor.isNull():
for c in customerList:
cursor.insertBlock()
cursor.insertText(c)
cursor.endEditBlock()
else:
oldcursor.endEditBlock()
def addParagraph(self, paragraph):
if not paragraph:
return
document = self.textEdit.document()
cursor = document.find("Yours sincerely,")
if cursor.isNull():
return
cursor.beginEditBlock()
cursor.movePosition(QtGui.QTextCursor.PreviousBlock, QtGui.QTextCursor.MoveAnchor, 2)
cursor.insertBlock()
cursor.insertText(paragraph)
cursor.insertBlock()
cursor.endEditBlock()
def about(self):
QtGui.QMessageBox.about(self, "About Dock Widgets",
"The <b>Dock Widgets</b> example demonstrates how to "
"use Qt's dock widgets. You can enter your own text, "
"click a customer to add a customer name and "
"address, and click standard paragraphs to add them.")
def createActions(self):
fileMenu = self.menuBar().addMenu("&File")
fileToolBar = self.addToolBar("File")
newIcon = QtGui.QIcon.fromTheme("document-new", QtGui.QIcon(":/images/new.png"))
newLetterAct = QtGui.QAction(newIcon, "&New Letter", self)
newLetterAct.setShortcuts(QtGui.QKeySequence.New)
newLetterAct.setStatusTip("Create a new form letter")
newLetterAct.triggered.connect(self.newLetter)
fileMenu.addAction(newLetterAct)
fileToolBar.addAction(newLetterAct)
saveIcon = QtGui.QIcon.fromTheme("document-save", QtGui.QIcon(":/images/save.png"))
saveAct = QtGui.QAction(saveIcon, "&Save...", self)
saveAct.setShortcuts(QtGui.QKeySequence.Save)
saveAct.setStatusTip("Save the current form letter")
saveAct.triggered.connect(self.save)
fileMenu.addAction(saveAct)
fileToolBar.addAction(saveAct)
printIcon = QtGui.QIcon.fromTheme("document-print", QtGui.QIcon(":/images/print.png"))
printAct = QtGui.QAction(printIcon,"&Print...", self)
printAct.setShortcuts(QtGui.QKeySequence.Print)
printAct.setStatusTip("Print the current form letter")
printAct.triggered.connect(self.print_)
fileMenu.addAction(printAct)
fileToolBar.addAction(printAct)
fileMenu.addSeparator()
quitAct = fileMenu.addAction("&Quit", self.close)
quitAct.setShortcuts(QtGui.QKeySequence.Quit)
quitAct.setStatusTip("Quit the application")
editMenu = self.menuBar().addMenu("&Edit")
editToolBar = self.addToolBar("Edit")
undoIcon = QtGui.QIcon.fromTheme("edit-undo", QtGui.QIcon(":/images/undo.png"))
undoAct = QtGui.QAction(undoIcon, "&Undo", self)
undoAct.setShortcuts(QtGui.QKeySequence.Undo)
undoAct.setStatusTip("Undo the last editing action")
undoAct.triggered.connect(self.undo)
editMenu.addAction(undoAct)
editToolBar.addAction(undoAct)
self.viewMenu = self.menuBar().addMenu("&View")
self.menuBar().addSeparator()
helpMenu = self.menuBar().addMenu("&Help")
aboutAct = helpMenu.addAction("&About", self.about)
aboutAct.setStatusTip("Show the application's About box")
aboutQtAct = helpMenu.addAction("About &Qt", QtGui.qApp.aboutQt)
aboutQtAct.setStatusTip("Show the Qt library's About box")
def createStatusBar(self):
self.statusBar().showMessage("Ready")
def createDockWindows(self):
dock = QtGui.QDockWidget("Customers", self)
dock.setAllowedAreas(QtCore.Qt.LeftDockWidgetArea | QtCore.Qt.RightDockWidgetArea)
self.customerList = QtGui.QListWidget(dock)
self.customerList.addItems([
"John Doe, Harmony Enterprises, 12 Lakeside, Ambleton",
"Jane Doe, Memorabilia, 23 Watersedge, Beaton",
"Tammy Shea, Tiblanka, 38 Sea Views, Carlton",
"Tim Sheen, Caraba Gifts, 48 Ocean Way, Deal",
"Sol Harvey, Chicos Coffee, 53 New Springs, Eccleston",
"Sally Hobart, Tiroli Tea, 67 Long River, Fedula"])
dock.setWidget(self.customerList)
self.addDockWidget(QtCore.Qt.RightDockWidgetArea, dock)
self.viewMenu.addAction(dock.toggleViewAction())
dock = QtGui.QDockWidget("Paragraphs", self)
self.paragraphsList = QtGui.QListWidget(dock)
self.paragraphsList.addItems([
"""Thank you for your payment which we have received today.""",
"""Your order has been dispatched and should be with you \
within 28 days.""",
"""We have dispatched those items that were in stock. The \
rest of your order will be dispatched once all the \
remaining items have arrived at our warehouse. No \
additional shipping charges will be made.""",
"""You made a small overpayment (less than $5) which we \
will keep on account for you, or return at your request.""",
"""You made a small underpayment (less than $1), but we have \
sent your order anyway. We'll add this underpayment to \
your next bill.""",
"""Unfortunately you did not send enough money. Please remit \
an additional $. Your order will be dispatched as soon as \
the complete amount has been received.""",
"""You made an overpayment (more than $5). Do you wish to \
buy more items, or should we return the excess to you?"""])
dock.setWidget(self.paragraphsList);
self.addDockWidget(QtCore.Qt.RightDockWidgetArea, dock)
self.viewMenu.addAction(dock.toggleViewAction())
self.customerList.currentTextChanged.connect(self.insertCustomer)
self.paragraphsList.currentTextChanged.connect(self.addParagraph)
# import dockwidgets_rc
if __name__ == '__main__':
import sys
app = QtGui.QApplication(sys.argv)
w = MainWindow()
w.show()
sys.exit(app.exec_())
The complete example can be found at the following link. The .qrc file has been compiled for Python 2 (dockwidgets_rc.py), but for Python 3 you must recompile the file.
I have a simple python QT multiplication program. There are 3 fields, first random number(read only), second random number(read only) and third line edit for user to input result. If first * second = result then show Right Label, else show Wrong Label. I would like to replace exit button with play again button, so when the user press it, to regenerate random numbers and clear all result labels and user try again.
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
def _fromUtf8(s):
return s
try:
_encoding = QtGui.QApplication.UnicodeUTF8
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig)
class Ui_Form(object):
def setupUi(self, Form):
Form.setObjectName(_fromUtf8("Form"))
Form.resize(650, 644)
self.label_71 = QtGui.QLabel(Form)
self.label_71.setGeometry(QtCore.QRect(70, 20, 481, 41))
font = QtGui.QFont()
font.setFamily(_fromUtf8("Andika"))
font.setPointSize(26)
self.label_71.setFont(font)
self.label_71.setObjectName(_fromUtf8("label_71"))
self.layoutWidget = QtGui.QWidget(Form)
self.layoutWidget.setGeometry(QtCore.QRect(200, 570, 221, 29))
self.layoutWidget.setObjectName(_fromUtf8("layoutWidget"))
self.horizontalLayout_51 = QtGui.QHBoxLayout(self.layoutWidget)
self.horizontalLayout_51.setMargin(0)
self.horizontalLayout_51.setObjectName(_fromUtf8("horizontalLayout_51"))
self.pushButton_2 = QtGui.QPushButton(self.layoutWidget)
self.pushButton_2.setObjectName(_fromUtf8("pushButton_2"))
self.pushButton_2.clicked.connect(self.exit_)
self.horizontalLayout_51.addWidget(self.pushButton_2)
self.pushButton = QtGui.QPushButton(self.layoutWidget)
font = QtGui.QFont()
font.setBold(True)
font.setWeight(75)
self.pushButton.setFont(font)
self.pushButton.setObjectName(_fromUtf8("pushButton"))
self.pushButton.clicked.connect(self.praxis)
self.horizontalLayout_51.addWidget(self.pushButton)
### Line Edit 1 - 2 ###
self.count = 124
self.list_x1 = []
self.list_y1 = []
for i in range(10):
self.x1 = randint(2,9)
self.list_x1.append(self.x1)
self.ln1 = "self.lineEdit1_" + str(i)
self.ln1 = QtGui.QLineEdit(Form)
self.ln1.setText(str(self.x1))
self.ln1.setReadOnly(True)
self.ln1.setGeometry(QtCore.QRect(74, self.count, 40, 26))
self.ln1.setAlignment(QtCore.Qt.AlignCenter)
self.ln1.setObjectName(_fromUtf8("lineEdit"))
self.y1 = randint(2,9)
self.list_y1.append(self.y1)
self.ln2 = "self.lineEdit2_" + str(i)
self.ln2 = QtGui.QLineEdit(Form)
self.ln2.setText(str(self.y1))
self.ln2.setReadOnly(True)
self.ln2.setGeometry(QtCore.QRect(140, self.count, 40, 26))
self.ln2.setAlignment(QtCore.Qt.AlignCenter)
self.ln2.setObjectName(_fromUtf8("lineEdit_2"))
self.count += 35
#Εισαγωγή 1ης στήλης
self.count = 124
self.ln3_value = []
for i in range(10):
self.ln3 = "self.lineEdit3_" + str(i)
self.ln3_value.append(self.ln3)
self.ln3_value[i] = QtGui.QLineEdit(Form)
self.ln3_value[i].setGeometry(QtCore.QRect(206, self.count, 40, 26))
self.ln3_value[i].setAlignment(QtCore.Qt.AlignCenter)
self.ln3_value[i].setObjectName(_fromUtf8("lineEdit_3"))
self.count += 35
### Line Edit 3- 4 ###
self.count = 124
self.list_x2 = []
self.list_y2 = []
for i in range(10):
self.x2 = randint(2,9)
self.list_x2.append(self.x2)
self.ln4 = "self.lineEdit4_" + str(i)
self.ln4 = QtGui.QLineEdit(Form)
self.ln4.setText(str(self.x2))
self.ln4.setReadOnly(True)
self.ln4.setGeometry(QtCore.QRect(348, self.count, 40, 26))
self.ln4.setAlignment(QtCore.Qt.AlignCenter)
self.ln4.setObjectName(_fromUtf8("lineEdit_4"))
self.y2 = randint(2,9)
self.list_y2.append(self.y2)
self.ln5 = "self.lineEdit5_" + str(i)
self.ln5 = QtGui.QLineEdit(Form)
self.ln5.setText(str(self.y2))
self.ln5.setReadOnly(True)
self.ln5.setGeometry(QtCore.QRect(414, self.count, 40, 26))
self.ln5.setAlignment(QtCore.Qt.AlignCenter)
self.ln5.setObjectName(_fromUtf8("lineEdit_5"))
self.count += 35
#Εισαγωγή 2ης στήλης
self.count = 124
self.ln6_value = []
for i in range(10):
self.ln6 = "self.lineEdit5_" + str(i)
self.ln6_value.append(self.ln3)
self.ln6_value[i] = QtGui.QLineEdit(Form)
self.ln6_value[i].setGeometry(QtCore.QRect(480, self.count, 40, 26))
self.ln6_value[i].setAlignment(QtCore.Qt.AlignCenter)
self.ln6_value[i].setObjectName(_fromUtf8("lineEdit_6"))
self.count += 35
### / Line Edit 1 - 4 ###
### Labels 1 - 6 ###
self.lbl1_count = 119
for i in range(10):
self.lbl_1 = "self.label1_" + str(i)
self.lbl_1 = QtGui.QLabel(Form)
self.lbl_1.setGeometry(QtCore.QRect(120, self.lbl1_count, 14, 34))
self.lbl_1.setText(_translate("Form", "X", None))
font = QtGui.QFont()
font.setFamily(_fromUtf8("Andika"))
font.setPointSize(16)
self.lbl_1.setFont(font)
self.lbl_1.setObjectName(_fromUtf8("label"))
self.lbl1_count += 35
self.lbl2_count = 119
for i in range(10):
self.lbl_2 = "self.label2_" + str(i)
self.lbl_2 = QtGui.QLabel(Form)
self.lbl_2.setGeometry(QtCore.QRect(186, self.lbl2_count, 14, 34))
self.lbl_2.setText(_translate("Form", "=", None))
font = QtGui.QFont()
font.setFamily(_fromUtf8("Andika"))
font.setPointSize(16)
self.lbl_2.setFont(font)
self.lbl_2.setObjectName(_fromUtf8("label_2"))
self.lbl2_count += 35
self.lbl3_list = []
self.lbl3_count = 119
for i in range(10):
self.lbl_3 = "self.label3_" + str(i)
self.lbl3_list.append(self.lbl_3)
self.lbl3_list[i] = QtGui.QLabel(Form)
self.lbl3_list[i].setGeometry(QtCore.QRect(252, self.lbl3_count, 80, 34))
self.lbl3_list[i].setText(_translate("Form", "?", None))
font = QtGui.QFont()
font.setFamily(_fromUtf8("Andika"))
font.setPointSize(14)
self.lbl3_list[i].setFont(font)
self.lbl3_list[i].setObjectName(_fromUtf8("label_3"))
self.lbl3_count += 35
self.lbl4_count = 119
for i in range(10):
self.lbl_4 = "self.label2_" + str(i)
self.lbl_4 = QtGui.QLabel(Form)
self.lbl_4.setGeometry(QtCore.QRect(394, self.lbl4_count, 14, 34))
self.lbl_4.setText(_translate("Form", "X", None))
font = QtGui.QFont()
font.setFamily(_fromUtf8("Andika"))
font.setPointSize(16)
self.lbl_4.setFont(font)
self.lbl_4.setObjectName(_fromUtf8("label_2"))
self.lbl4_count += 35
self.lbl5_count = 119
for i in range(10):
self.lbl_5 = "self.label5_" + str(i)
self.lbl_5 = QtGui.QLabel(Form)
self.lbl_5.setGeometry(QtCore.QRect(460, self.lbl5_count, 14, 34))
self.lbl_5.setText(_translate("Form", "=", None))
font = QtGui.QFont()
font.setFamily(_fromUtf8("Andika"))
font.setPointSize(16)
self.lbl_5.setFont(font)
self.lbl_5.setObjectName(_fromUtf8("label_5"))
self.lbl5_count += 35
self.lbl6_list = []
self.lbl6_count = 119
for i in range(10):
self.lbl_6 = "self.label6_" + str(i)
self.lbl6_list.append(self.lbl_6)
self.lbl6_list[i] = QtGui.QLabel(Form)
self.lbl6_list[i].setGeometry(QtCore.QRect(526, self.lbl6_count, 80, 34))
self.lbl6_list[i].setText(_translate("Form", "?", None))
font = QtGui.QFont()
font.setFamily(_fromUtf8("Andika"))
font.setPointSize(14)
self.lbl6_list[i].setFont(font)
self.lbl6_list[i].setObjectName(_fromUtf8("label_6"))
self.lbl6_count += 35
### / Labels 1 - 6 ###
self.retranslateUi(Form)
QtCore.QMetaObject.connectSlotsByName(Form)
def retranslateUi(self, Form):
Form.setWindowTitle(_translate("Form", "Multiplication", None))
self.label_71.setText(_translate("Form", "Multiplication", None))
self.pushButton_2.setText(_translate("Form", "Exit", None))
self.pushButton.setText(_translate("Form", "Check", None))
def praxis(self):
self.lbl3_count = 119
for i in range(10):
self.val = self.ln3_value[i]
self.val2 = self.ln6_value[i]
self.get_val = self.val.text()
self.get_val2 = self.val2.text()
self.get_val_str = str(self.get_val)
self.get_val2_str = str(self.get_val2)
self.summary = self.list_y1[i] * self.list_x1[i]
self.summary2 = self.list_y2[i] * self.list_x2[i]
self.summary_int = str(self.summary)
self.summary_int2 = str(self.summary2)
if self.summary_int == self.get_val_str:
self.lbl3_list[i].setText(_translate("Form", "Σωστό!", None))
self.lbl3_list[i].setStyleSheet('color: green')
else:
self.lbl3_list[i].setText(_translate("Form", "Λάθος!", None))
self.lbl3_list[i].setStyleSheet('color: red')
if self.summary_int2 == self.get_val2_str:
self.lbl6_list[i].setText(_translate("Form", "Σωστό!", None))
self.lbl6_list[i].setStyleSheet('color: green')
else:
self.lbl6_list[i].setText(_translate("Form", "Λάθος!", None))
self.lbl6_list[i].setStyleSheet('color: red')
def exit_(self):
import sys
sys.exit()
if __name__ == "__main__":
import sys
app = QtGui.QApplication(sys.argv)
Form = QtGui.QWidget()
ui = Ui_Form()
ui.setupUi(Form)
Form.show()
sys.exit(app.exec_())