In Python, how to use GUI module file created in QtDesigner - python-3.x

I created a GUI with the hepl of QtCreator-->QtDesigner. The file is called mainwindow.ui. With the help of pyuic5 I created mainwindow.py
pyuic5 mainwindow.ui > mainwindow.py
and this is how it looks like:
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(400, 300)
self.centralWidget = QtWidgets.QWidget(MainWindow)
self.centralWidget.setObjectName("centralWidget")
self.frame = QtWidgets.QFrame(self.centralWidget)
self.frame.setGeometry(QtCore.QRect(30, 20, 341, 191))
self.frame.setFrameShape(QtWidgets.QFrame.Panel)
self.frame.setFrameShadow(QtWidgets.QFrame.Sunken)
self.frame.setObjectName("frame")
MainWindow.setCentralWidget(self.centralWidget)
self.menuBar = QtWidgets.QMenuBar(MainWindow)
self.menuBar.setGeometry(QtCore.QRect(0, 0, 400, 23))
self.menuBar.setObjectName("menuBar")
MainWindow.setMenuBar(self.menuBar)
self.mainToolBar = QtWidgets.QToolBar(MainWindow)
self.mainToolBar.setObjectName("mainToolBar")
MainWindow.addToolBar(QtCore.Qt.TopToolBarArea, self.mainToolBar)
self.statusBar = QtWidgets.QStatusBar(MainWindow)
self.statusBar.setObjectName("statusBar")
MainWindow.setStatusBar(self.statusBar)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
and wanted to import that in my main script main.py:
#!/usr/bin/env python3
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from mainwindow import *
import sys
def main():
app = QApplication(sys.argv)
instance = Ui_MainWindow()
#instance.show()
sys.exit(app.exec_())
if __name__ == "__main__":
main()
...but nothing happens when I run it. How should my main.py look like to use that gui module?

Ok, I figured it myself. To use a GUI file in Python, created in QtCreator called mainwindow.py, my main.py should look something like this:
#!/usr/bin/env python3
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from mainwindow import *
import sys
class Main(QMainWindow):
def __init__(self):
super().__init__()
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
self.show()
def main():
app = QApplication(sys.argv)
instance = Main()
#instance.show()
sys.exit(app.exec_())
if __name__ == "__main__":
main()
My class Main(QMainWindow) must have a parent QMainWindow and not QWidget because QWidget doesn't have setCentralWidget method which is needed in mainwindow.py.

Related

AttributeError: 'QWidget' object has no attribute 'tk'. Did you mean: 'tr'? PyQt5 Python

I am trying to make canvas for PyQt5 GUI. For this, I've used TkInter's canvas property. So I created a new widget in Qt Designer for tkinter's canvas.
As you can see from the picture below, I created promoted class for QWidget to use Canvas.
Then I converted this GUI into python code.
When I try to run my GUI, I'm getting the error which is on the title.
That's normal code:
from sympy import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from tkinter.messagebox import *
import sympy
import sys
from tkinter import Canvas
from untitled import *
class canvastrying(QMainWindow):
def __init__(self) -> None:
super().__init__()
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
if __name__ == "__main__":
app = QApplication(sys.argv)
window = canvastrying()
sys.exit(app.exec_())
That's my GUI's code:
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(318, 325)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.widget = Canvas(self.centralwidget)
self.widget.setGeometry(QtCore.QRect(10, 20, 291, 231))
self.widget.setStyleSheet("background-color: green;")
self.widget.setObjectName("widget")
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 318, 21))
self.menubar.setObjectName("menubar")
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtWidgets.QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
from tkinter import Canvas
Can we use TkInter's canvas property in PyQt5? If we can, what am I doing wrong?

How get text from QTextEdit in Pyqt5? [duplicate]

This question already has an answer here:
Get text from qtextedit and assign it to a variable
(1 answer)
Closed 2 years ago.
I need get text from QTextEdit, but have such trouble: Traceback (most recent call last):
File "main.py", line 28, in otpravit_naz
textboxValue = self.textEdit.text()
AttributeError: 'MyWin' object has no attribute 'textEdit'
This is my code(main.py):
import sys
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from test import *
import socket
sock = socket.socket()
class MyWin(QtWidgets.QMainWindow):
def __init__(self, parent=None):
QtWidgets.QWidget.__init__(self, parent)
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
self.ui.otpravit.clicked.connect(self.otpravit_naz)
def mbox(self, body, title='Error'):
dialog = QMessageBox(QMessageBox.Information, title, body)
dialog.exec_()
def otpravit_naz(self):
print("1")
textboxValue = self.textEdit.text()
print(textboxValue)
#sock.connect(('192.168.1.16', 9090))
sock.connect(("192.168.1.45", 9090))
sock.send(b'textboxValue')
sock.close()
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
myapp = MyWin()
myapp.show()
sys.exit(app.exec_())
And ui form:
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(517, 283)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.verticalLayoutWidget = QtWidgets.QWidget(self.centralwidget)
self.verticalLayoutWidget.setGeometry(QtCore.QRect(60, 20, 421, 201))
self.verticalLayoutWidget.setObjectName("verticalLayoutWidget")
self.verticalLayout = QtWidgets.QVBoxLayout(self.verticalLayoutWidget)
self.verticalLayout.setSizeConstraint(QtWidgets.QLayout.SetFixedSize)
self.verticalLayout.setContentsMargins(0, 0, 0, 0)
self.verticalLayout.setSpacing(23)
self.verticalLayout.setObjectName("verticalLayout")
self.textEdit = QtWidgets.QTextEdit(self.verticalLayoutWidget)
self.textEdit.setObjectName("textEdit")
self.verticalLayout.addWidget(self.textEdit)
self.label = QtWidgets.QLabel(self.verticalLayoutWidget)
self.label.setLineWidth(0)
self.label.setMidLineWidth(0)
self.label.setAlignment(QtCore.Qt.AlignCenter)
self.label.setObjectName("label")
self.verticalLayout.addWidget(self.label)
self.list = QtWidgets.QComboBox(self.verticalLayoutWidget)
self.list.setObjectName("list")
self.list.addItem("")
self.list.addItem("")
self.list.addItem("")
self.verticalLayout.addWidget(self.list)
self.otpravit = QtWidgets.QPushButton(self.verticalLayoutWidget)
self.otpravit.setObjectName("otpravit")
self.verticalLayout.addWidget(self.otpravit)
self.verticalLayout.setStretch(0, 20)
self.verticalLayout.setStretch(1, 20)
self.verticalLayout.setStretch(2, 20)
self.verticalLayout.setStretch(3, 20)
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 517, 21))
self.menubar.setObjectName("menubar")
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtWidgets.QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.label.setText(_translate("MainWindow", "Предмет:"))
self.list.setItemText(0, _translate("MainWindow", "Русский"))
self.list.setItemText(1, _translate("MainWindow", "Литература"))
self.list.setItemText(2, _translate("MainWindow", "Английский"))
self.otpravit.setText(_translate("MainWindow", "Отправить"))
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_())
If it very stupid troble, pls don't kick me
You're "installing" the GUI on the self.ui object, so every widget that is on the ui is actually accessible as self.ui.someWidget.
Also, QTextEdit doesn't have a text() property, but toPlainText():
def otpravit_naz(self):
print("1")
textboxValue = self.ui.textEdit.toPlainText()
print(textboxValue)
I suggest you to never edit the files generated with pyuic, but always use them as imported modules; read more on using Designer; also, be careful to set the main layout on the central widget, not on its children, and add everything to that layout, otherwise the children widgets could be hidden whenever the window is resized.

keyPressEvent is not working in my PyQt application

I am trying to use keyPressEvent in a mainwindow I generated with QtDesigner but no key press is detected by my program. Here is my code
The QtDesigner generated class is MainWindowUI.
class MainWindow(QMainWindow,MainWindowUI.Ui_MainWindow):
def __init__(self, translator,parent=None):
QMainWindow.__init__(self, parent=parent)
#super(MainWindow,self).__init__(parent)
self.setupUi(self)
self.translator=translator
self.completeGUI()
def completeGUI(self):
self.setConnections()
self.set_line_edit_validators()
self.category_combo.insertSeparator(4)
self.category_combo.insertSeparator(8)
self.type_conjug_combo.insertSeparator(3)
self.type_conjug_combo.insertSeparator(6)
#self.type_conjug_combo.setItemData( 0, QtGui.QColor('red'), QtCore.Qt.ForegroundRole )
self.save_button.clicked.connect(self.fileSave)
self.category_label.hide()
self.category_combo.hide()
self.type_conjug_label.hide()
self.type_conjug_combo.hide()
self.grammar_combo.setStyleSheet("color:red")
self.category_combo.setStyleSheet("color:red;")
self.type_conjug_combo.setStyleSheet("color:red;")
self.palat_combo.setStyleSheet("color:red;")
self.accent_combo.setStyleSheet("color:red;")
self.terme_edit.setStyleSheet("border: 2px solid red;")
print("completeGUI is over")
def keyPressEvent(self, e):
print(e.key())
I had a look at various answers to analog question on this forum but I could not manage to have it working.
Thank you for help.
HERE IS A MINIMAL EXAMPLE THAT REPRODUCES THE TROUBLE
from PyQt5 import QtCore
from PyQt5.QtWidgets import QApplication
import sys
from view.NewMainWindow import NewMainWindow
if __name__=='__main__':
app = QApplication(sys.argv)
translator = QtCore.QTranslator()
app.installTranslator(translator)
mainWindow = NewMainWindow(translator)
NewMainWindow.show(mainWindow)
#sys.exit(app.exec_())
current_exit_code=app.exec_()
app=None
AND THE NEWMAINWINDOW
from PyQt5.QtWidgets import QMainWindow
from gen import NewMainWindowUI
class NewMainWindow(QMainWindow,NewMainWindowUI.Ui_MainWindow):
def __init__(self,translator, parent=None):
super(NewMainWindow,self).__init__(parent)
self.setupUi(self)
print('init completed')
def keyPressEvent(self, e):
print('event detected')
print(e.key())
THE GENERATED INTERFACE
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'src/designer/newmainwindow.ui'
#
# Created by: PyQt5 UI code generator 5.13.1
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(800, 600)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.lineEdit = QtWidgets.QLineEdit(self.centralwidget)
self.lineEdit.setGeometry(QtCore.QRect(130, 110, 113, 36))
self.lineEdit.setObjectName("lineEdit")
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 29))
self.menubar.setObjectName("menubar")
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtWidgets.QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
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 usually avoid calling a keyPressEvent from both the central widget and the main window, because, as #musicamante said, one could be "consuming" the other. Especially if you plan on switching between multiple central widgets.
You should instead create a slot on a QMainWindow object connected to the central widget's keyPressEvent (but name it something else, like onKeyPressEvent or something) and then you emit the event from inside the MainWindow's keyPressEvent, something like this:
from PyQt5.QtWidgets import QApplication, QMainWindow, QWidget
from PyQt5.QtCore import pyqtSignal, pyqtSlot
from PyQt5.QtGui import QKeyEvent
class MainWindow(QMainWindow):
key_pressed = pyqtSignal(QKeyEvent)
def __init__(self, *args, **kwargs) -> None:
super().__init__(*args, **kwargs)
central_widget = NewWindow()
self.key_pressed.connect(central_widget.onKeyPressEvent)
self.setCentralWidget(central_widget)
...
def keyPressEvent(self, event: QKeyEvent) -> None:
self.key_pressed.emit(event)
return super().keyPressEvent(event)
class NewWindow(QWidget):
def __init__(self, *args, **kwargs) -> None:
super().__init__(*args, **kwargs)
...
#pyqtSlot(QKeyEvent)
def onKeyPressEvent(self, event: QKeyEvent) -> None:
print(event.key())
return

Embed a Matplotlib graphic into a widget - PyQt5

I would like to embed a graphic from Matplotlib into an existing GUI containing a Widget and a PushButton developed from QtDesigner and PyQt5. I can embed the graphic but can't resize the graphic to take all space available/needed into the Widget.
Front end code:
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(595, 393)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.gridLayout = QtWidgets.QGridLayout(self.centralwidget)
self.gridLayout.setObjectName("gridLayout")
self.pushButton = QtWidgets.QPushButton(self.centralwidget)
self.pushButton.setMaximumSize(QtCore.QSize(100, 16777215))
self.pushButton.setObjectName("pushButton")
self.gridLayout.addWidget(self.pushButton, 0, 0, 1, 1)
self.widget = QtWidgets.QWidget(self.centralwidget)
self.widget.setMinimumSize(QtCore.QSize(0, 200))
self.widget.setStyleSheet("background-color: rgb(255, 255, 255);")
self.widget.setObjectName("widget")
self.gridLayout.addWidget(self.widget, 0, 1, 1, 1)
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 595, 21))
self.menubar.setObjectName("menubar")
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtWidgets.QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.pushButton.setText(_translate("MainWindow", "PushButton"))
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_())
Back end code:
import sys
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QMainWindow, QApplication, QWidget, QSizePolicy
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar
from matplotlib.figure import Figure
from front_end import Ui_MainWindow
class Graph_init(FigureCanvas):
def __init__(self, parent=None):
fig = Figure()
self.axes = fig.add_subplot(111)
self.compute_initial_figure()
FigureCanvas.__init__(self, fig)
self.setParent(parent)
FigureCanvas.setSizePolicy(self, QSizePolicy.Expanding, QSizePolicy.Expanding)
FigureCanvas.updateGeometry(self)
class Graph_populate(Graph_init):
def compute_initial_figure(self):
x = [2000,2001,2002,2003,2004]
y = [10,20,30,40,50]
self.axes.plot(x, y)
class GUI(QMainWindow, Ui_MainWindow):
def __init__(self, parent=None):
super(GUI, self).__init__(parent)
self.setupUi(self)
self.sc = Graph_populate(self.widget)
if __name__ == '__main__':
app = QApplication(sys.argv)
prog = GUI()
prog.showMaximized()
sys.exit(app.exec_())
Thank you
In PyQt you would normally add a widget to your application by adding it to a Layout. In the code you seem to have forgotten to do that step.
So if self.gridLayout is the layout you want your FigureCanvas to reside in, you would need to add the latter to the former as
self.gridLayout.addWidget(self.sc, 0, 1, 1, 1)
The role of self.widget on the other hand is not really clear here and you may probably remove it. The self.centralwidget can take the role of the parent, if it is really needed,
self.sc = Graph_populate(self.centralwidget)

Pyqt5: builtins.AttributeError: 'QDialog' object has no attribute 'setCentralWidget'

I converted ui file from Pyqt5 designer:
Testing1.py
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(800, 600)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.pushButton = QtWidgets.QPushButton(self.centralwidget)
self.pushButton.setGeometry(QtCore.QRect(380, 180, 112, 34))
self.pushButton.setObjectName("pushButton")
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 31))
self.menubar.setObjectName("menubar")
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtWidgets.QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.pushButton.setText(_translate("MainWindow", "PushButton"))
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_())
Test1.py < is meant to add methods etc. etc.
import sys
from PyQt5 import QtWidgets, QtCore, QtGui
from testing1 import Ui_MainWindow
class myprog(Ui_MainWindow):
def __init__ (self, dialog):
Ui_MainWindow.__init__(self)
self.setupUi(dialog)
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
dialog = QtWidgets.QDialog()
test1 = myprog(dialog)
dialog.show()
sys.exit(app.exec_())
If I run Testin1.py it's all ok, but if run second script, test1.py, i get following message:
> builtins.AttributeError: 'QDialog' object has no attribute
> 'setCentralWidget'
I am really confused what to do, I would really really appreciate, if you could help me solve this problem. Any help is more than welcome.
In Testing1.py file, you create a MainWindow.
So in your Test1.py file, you should change the code
dialog = QtWidgets.QDialog()
to
dialog = QtWidgets.QMainWindow()

Resources