Two days ago, i begun to study python in order to develop a lesson project. With my team we wrote the code bellow. Is a simple first screen with one image, two labels and a menu bar.
import sys
from PyQt5.QtWidgets import QMainWindow, QApplication, QWidget, QPushButton, QAction, QMenu, QLabel, QTextEdit
from PyQt5.QtGui import QIcon, QPixmap
from PyQt5 import QtCore
class Example(QMainWindow):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.left = 10
self.top = 10
self.width = 640
self.height = 480
menubar = self.menuBar()
#MEnubar horizontal
fileMenu = menubar.addMenu('Indoor Models')
fileMenu2 = menubar.addMenu('Outdoor Models')
fileMenu3 = menubar.addMenu('Report')
fileMenu4 = menubar.addMenu('About')
#menubar vertical column 1
newAct = QAction('Free Space Lost', self)
newAct2 = QAction('Okumura', self)
newAct3 = QAction('Hata', self)
newAct4 = QAction('COST 211', self)
fileMenu.addAction(newAct)
fileMenu.addAction(newAct2)
fileMenu.addAction(newAct3)
fileMenu.addAction(newAct4)
#menubar vertical column 2
newAct = QAction('Okumura', self)
newAct2 = QAction('Okumura', self)
newAct3 = QAction('Hata', self)
newAct4 = QAction('COST 211', self)
fileMenu2.addAction(newAct)
fileMenu2.addAction(newAct2)
fileMenu2.addAction(newAct3)
fileMenu2.addAction(newAct4)
self.setGeometry(300, 100, 800, 600)
#stylesheet LABEL HEADER
self.setStyleSheet("QLabel {color: #3391EF; qproperty-alignment: AlignCenter}")
label = QLabel('<font size=14><strong>Propagation Models</strong></font>', self)
label.setGeometry(QtCore.QRect(230, 40, 300, 100))
#LABEL FOR IMAGE
label2 = QLabel(self)
label2.setGeometry(QtCore.QRect(140, 140, 500, 200))
pixmap = QPixmap('1.png')
label2.setPixmap(pixmap)
label3 = QLabel('<font size=14><strong><u>Description</u></strong></font>', self)
label3.setGeometry(QtCore.QRect(230, 350, 300, 100))
self.show()
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
The next step is when we click an object to a menu bar (for example "Hata"), we want to open a new window. We stuck to this step... Any idea that could help us in this situation?
The first thing you must learn is that in PyQt you should try to do everything asynchronously, for that you must use the signals, these are emits when an event happens, in your particular case every time you press a QAction
the triggered signal is emitted, you must connect This signal to some function that you want to be called when the event happens, in PyQt that function is called Slot. In that Slot you must do the task you want, in this case I will show a QDialog
:
class Example(QMainWindow):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
...
self.show()
newAct3.triggered.connect(self.on_triggered)
@QtCore.pyqtSlot()
def on_triggered(self):
w = QDialog(self)
w.resize(640, 480)
w.exec_()
...