I wanted to create a secondary window to show the fullsized image, so that's what I've made but I can't see the image. I don't know if it's why I don't open correctly or what. I'm very new to Qt so provably it's a very simple mistake.
Thanks
Here's the code:
import sys
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QMessageBox
This is the main window, it has a open file dialog to select an image, once it have it puts the image in a label. When you click the button "Ampliar" you open a second window with should show the image with the original size.
# Classe per la finestra principal de l'App
class Ui_MainWindow(object):
# Inicialitzacio de variables
def __init__(self):
self.fileName = None
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(1080, 720)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
# Label on coloquem la nostra imatge
self.lMarcIm = QtWidgets.QLabel(self.centralwidget)
self.lMarcIm.setGeometry(QtCore.QRect(10, 10, 500, 500))
self.lMarcIm.setAutoFillBackground(False)
self.lMarcIm.setScaledContents(True)
self.lMarcIm.setObjectName("lMarcIm")
# Boto per carregar una imatge al programa
self.bObrirIm = QtWidgets.QPushButton(self.centralwidget)
self.bObrirIm.setGeometry(QtCore.QRect(10, 530, 111, 31))
self.bObrirIm.setObjectName("bObrirIm")
self.bObrirIm.clicked.connect(self.obrirDialegImatge)
# Boto per ampliar la imatge carregada
self.bAmpliarIm = QtWidgets.QPushButton(self.centralwidget)
self.bAmpliarIm.setGeometry(QtCore.QRect(130, 530, 121, 31))
self.bAmpliarIm.setObjectName("bAmpliarIm")
self.bAmpliarIm.clicked.connect(self.ampliarImatge)
MainWindow.setCentralWidget(self.centralwidget)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
################################################################
# Bloc de Funcions #
################################################################
def obrirDialegImatge(self):
# Obrim la finestra de dialeg i obtenim el nom
options = QtWidgets.QFileDialog.Options()
options |= QtWidgets.QFileDialog.DontUseNativeDialog
self.fileName, _ = QtWidgets.QFileDialog.getOpenFileName(
None,
"QFileDialog.getOpenFileName()",
"",
"All Files (*);;Python Files (*.py)",
options=options)
# Posem l'imatge on toca del Layout
self.lMarcIm.setPixmap(QtGui.QPixmap(self.fileName))
def ampliarImatge(self):
#Comprovem que hi ha una imatge seleccionada
if self.fileName != None:
print("Imatge en gran")
self.openSecondWindow()
else:
self.popup_errorAmpliar()
def openSecondWindow(self):
self.secondWindow = QtWidgets.QMainWindow()
self.ui = Ui_SecondaryWindow()
self.ui.setupUi(self.secondWindow, self.fileName)
self.secondWindow.show()
def popup_errorAmpliar(self):
msg = QMessageBox()
msg.setWindowTitle("Alerta!")
msg.setText("No hi ha cap imatge carregada")
msg.setIcon(QMessageBox.Warning)
x = msg.exec_()
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "Image Processing APP"))
self.lMarcIm.setText(_translate("MainWindow", "TextLabel"))
self.bObrirIm.setText(_translate("MainWindow", "Obrir Imatge"))
self.bAmpliarIm.setText(_translate("MainWindow", "Ampliar"))
This is the secondary class, where I want to put the image I open in the other window, it recive it's path so I think it has to be easy
# Classe per la finestra secundaria de l'App
class Ui_SecondaryWindow(object):
def setupUi(self, SecondaryWindow, im):
SecondaryWindow.setObjectName("SecondaryWindow")
SecondaryWindow.resize(800, 600)
self.centralwidget = QtWidgets.QWidget(SecondaryWindow)
self.centralwidget.setObjectName("centralwidget")
self.lmidaOriginal = QtWidgets.QLabel(self.centralwidget)
self.lmidaOriginal.setGeometry(QtCore.QRect(150, 60, 251, 101))
self.lmidaOriginal.setObjectName("lmidaOriginal")
self.openImage(im)
SecondaryWindow.setCentralWidget(self.centralwidget)
self.retranslateUi(SecondaryWindow)
QtCore.QMetaObject.connectSlotsByName(SecondaryWindow)
def openImage(self, imRoute):
print(imRoute)
pixmap = QtGui.QPixmap("imRoute")
self.lmidaOriginal.setPixmap(pixmap)
#self.lmidaOriginal.resize(pixmap.width(), pixmap.height())
def retranslateUi(self, SecondaryWindow):
_translate = QtCore.QCoreApplication.translate
SecondaryWindow.setWindowTitle(_translate("SecondaryWindow", "Apmliated Image"))
self.lmidaOriginal.setText(_translate("SecondaryWindow", "TextLabel"))
this is the main
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_())
Try it:
import sys
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QMessageBox
# Classe per la finestra secundaria de l'App
class Ui_SecondaryWindow(object):
def setupUi(self, SecondaryWindow): #, im):
SecondaryWindow.setObjectName("SecondaryWindow")
# SecondaryWindow.resize(800, 600)
self.centralwidget = QtWidgets.QWidget(SecondaryWindow)
self.centralwidget.setObjectName("centralwidget")
self.lmidaOriginal = QtWidgets.QLabel(self.centralwidget)
# self.lmidaOriginal.setGeometry(QtCore.QRect(150, 60, 251, 101))
self.lmidaOriginal.setObjectName("lmidaOriginal")
# self.openImage(im)
SecondaryWindow.setCentralWidget(self.centralwidget)
self.retranslateUi(SecondaryWindow)
QtCore.QMetaObject.connectSlotsByName(SecondaryWindow)
"""
def openImage(self, imRoute):
print("imRoute---", imRoute)
pixmap = QtGui.QPixmap("imRoute")
pixmap = QtGui.QPixmap(imRoute) #("im.png") #(imRoute)
self.lmidaOriginal.setPixmap(pixmap)
"""
def retranslateUi(self, SecondaryWindow):
_translate = QtCore.QCoreApplication.translate
SecondaryWindow.setWindowTitle(_translate("SecondaryWindow", "Apmliated Image"))
self.lmidaOriginal.setText(_translate("SecondaryWindow", "TextLabel"))
# Classe per la finestra principal de l'App
class Ui_MainWindow(object):
# Inicialitzacio de variables
def __init__(self):
self.fileName = None
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(1080, 720)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
# Label on coloquem la nostra imatge
self.lMarcIm = QtWidgets.QLabel(self.centralwidget)
self.lMarcIm.setGeometry(QtCore.QRect(10, 10, 500, 500))
self.lMarcIm.setAutoFillBackground(False)
self.lMarcIm.setScaledContents(True)
self.lMarcIm.setObjectName("lMarcIm")
# Boto per carregar una imatge al programa
self.bObrirIm = QtWidgets.QPushButton(self.centralwidget)
self.bObrirIm.setGeometry(QtCore.QRect(10, 530, 111, 31))
self.bObrirIm.setObjectName("bObrirIm")
self.bObrirIm.clicked.connect(self.obrirDialegImatge)
# Boto per ampliar la imatge carregada
self.bAmpliarIm = QtWidgets.QPushButton(self.centralwidget)
self.bAmpliarIm.setGeometry(QtCore.QRect(130, 530, 121, 31))
self.bAmpliarIm.setObjectName("bAmpliarIm")
self.bAmpliarIm.clicked.connect(self.ampliarImatge)
MainWindow.setCentralWidget(self.centralwidget)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
################################################################
# Bloc de Funcions #
################################################################
def obrirDialegImatge(self):
# Obrim la finestra de dialeg i obtenim el nom
options = QtWidgets.QFileDialog.Options()
options |= QtWidgets.QFileDialog.DontUseNativeDialog
self.fileName, _ = QtWidgets.QFileDialog.getOpenFileName(
None,
"Select Image",
"",
"Image Files (*.png *.jpg *.jpeg *.bmp)", # +++
options=options)
# Posem l'imatge on toca del Layout
self.lMarcIm.setPixmap(QtGui.QPixmap(self.fileName))
def ampliarImatge(self):
#Comprovem que hi ha una imatge seleccionada
if self.fileName != None:
print("Imatge en gran")
self.openSecondWindow()
else:
self.popup_errorAmpliar()
def openSecondWindow(self):
self.secondWindow = QtWidgets.QMainWindow()
self.ui = Ui_SecondaryWindow()
# self.ui.setupUi(self.secondWindow, self.fileName)
# +++ vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
self.ui.setupUi(self.secondWindow)
self.ui.lmidaOriginal.setPixmap(QtGui.QPixmap(self.fileName))
self.ui.lmidaOriginal.adjustSize()
self.secondWindow.resize(self.ui.lmidaOriginal.width(), self.ui.lmidaOriginal.height())
# +++ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
self.secondWindow.show()
def popup_errorAmpliar(self):
msg = QMessageBox()
msg.setWindowTitle("Alerta!")
msg.setText("No hi ha cap imatge carregada")
msg.setIcon(QMessageBox.Warning)
x = msg.exec_()
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "Image Processing APP"))
self.lMarcIm.setText(_translate("MainWindow", "TextLabel"))
self.bObrirIm.setText(_translate("MainWindow", "Obrir Imatge"))
self.bAmpliarIm.setText(_translate("MainWindow", "Ampliar"))
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_())
Related
I want to make that, when I press the plus, another same form is made.
The second form appeared but the first form was lost
I need help when I keep the first one and add the others below
from zlib import DEF_BUF_SIZE
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(459, 288)
self.y=15
self.x=20
self.i=0
self.rep(self.y, self.x)
self.retranslateUi(MainWindow)
#QtCore.QMetaObject.connectSlotsByName(MainWindow)
self.statusbar = QtWidgets.QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
def rep(self,x,y):
icon = QtGui.QIcon()
icon.addPixmap(QtGui.QPixmap("../../../Downloads/Hopstarter-Button-Button-Add.ico"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
MainWindow.setWindowIcon(icon)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget" + str(self.i))
self.lineEdit = QtWidgets.QLineEdit(self.centralwidget)
self.lineEdit.setGeometry(QtCore.QRect(30, x, 200, 30))
font = QtGui.QFont()
font.setPointSize(14)
font.setWeight(75)
self.lineEdit.setFont(font)
self.lineEdit.setObjectName("lineEdit")
self.pushButton = QtWidgets.QPushButton(self.centralwidget)
self.pushButton.setGeometry(QtCore.QRect(250, y, 75, 23))
self.pushButton.setText("")
self.pushButton.setIcon(icon)
self.pushButton.setIconSize(QtCore.Size(21, 21))
self.pushButton.setDefault(True)
self.pushButton.setObjectName("pushButton")
self.pushButton.clicked.connect(self.onOne)
MainWindow.setCentralWidget(self.centralwidget)
pass
def onOne(self):
self.y +=30
self.x +=30
self.i += 1
self.rep(self.y, self.x)
pass
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 tried the first suggestion and it didn't work. I listened to another suggestion. He modified something of his own, and it works
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import (QWidget, QPushButton,
QHBoxLayout, QVBoxLayout, QApplication)
class Ui_MainWindow(QWidget):
def __init__(self):
super().__init__()
self.vbox = QVBoxLayout()
self.setupUi()
def setupUi(self):
self.hbox = QHBoxLayout()
self.lineEdit = self.lab()
self.hbox.addWidget(self.lineEdit)
self.hbox.addStretch()
self.pushButton = self.butt()
self.hbox.addWidget(self.pushButton)
self.vbox.addLayout(self.hbox)
self.setLayout(self.vbox)
self.pushButton.clicked.connect(self.klik)
def klik(self):
s = self.lineEdit.text()
if (len(s.strip())!=0):
self.pushButton.setEnabled(False)
self.setupUi()
pass
def f(self):
font = QtGui.QFont()
font.setPointSize(14)
font.setBold(True)
font.setWeight(75)
return font
def i(self):
icon = QtGui.QIcon()
icon.addPixmap(QtGui.QPixmap("../../../Users/Downloads/Hopstarter-Button-Button-Add.ico"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
return icon
def butt(self):
pushButton = QtWidgets.QPushButton()
ff = self.f()
pushButton.setFont(ff)
pushButton.setLayoutDirection(QtCore.Qt.LeftToRight)
pushButton.setText("")
ii = self.i()
pushButton.setIcon(ii)
pushButton.setIconSize(QtCore.QSize(21, 21))
pushButton.setAutoDefault(True)
pushButton.setDefault(True)
pushButton.setFlat(True)
pushButton.setObjectName("pushButton")
return pushButton
def lab(self):
lineEdit = QtWidgets.QLineEdit()
ff = self.f()
lineEdit.setFont(ff)
lineEdit.setObjectName("lineEdit")
return lineEdit
if name == "main":
import sys
app = QtWidgets.QApplication(sys.argv)
ui = Ui_MainWindow()
ui.show()
sys.exit(app.exec_())
Below are the 2 window codes, 1st is main window and 2nd is widget window:
from Open import Ui_Form
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def open(self):
self.window = QtWidgets.QWidget()
self.ui = Ui_Form()
self.ui.setupUi(self.window)
self.window.show()
def get_result(self):
answer = []
Unsqueeze_result = set(answer)
final = list(Unsqueeze_result)
final.sort()
self.final_list = [x.upper() for x in final]
self.listView.addItems(self.final_list)
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(800, 600)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.listView = QtWidgets.QListView(self.centralwidget)
self.listView.setGeometry(QtCore.QRect(270, 140, 256, 371))
self.listView.setObjectName("listView")
self.result_button = QtWidgets.QPushButton(self.centralwidget)
self.result_button.setGeometry(QtCore.QRect(350, 70, 91, 41))
self.result_button.setObjectName("result_button")
self.result_button.pressed.connect(self.get_result)
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 21))
self.menubar.setObjectName("menubar")
self.menuFile = QtWidgets.QMenu(self.menubar)
self.menuFile.setObjectName("menuFile")
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtWidgets.QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
self.actionOpen = QtWidgets.QAction(MainWindow)
self.actionOpen.setObjectName("actionOpen")
self.actionOpen.triggered.connect(lambda:self.open())
self.menuFile.addAction(self.actionOpen)
self.menubar.addAction(self.menuFile.menuAction())
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.result_button.setText(_translate("MainWindow", "Result"))
self.menuFile.setTitle(_translate("MainWindow", "File"))
self.actionOpen.setText(_translate("MainWindow", "Open"))
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_())
Below are 2nd window:
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Form(object):
def __init__(self):
self.list_result = []
def setupUi(self, Form):
Form.setObjectName("Form")
Form.resize(400, 300)
self.checkBox_1 = QtWidgets.QCheckBox(Form)
self.checkBox_1.setGeometry(QtCore.QRect(60, 70, 121, 31))
self.checkBox_1.setObjectName("checkBox_1")
self.checkBox_2 = QtWidgets.QCheckBox(Form)
self.checkBox_2.setGeometry(QtCore.QRect(60, 110, 111, 31))
self.checkBox_2.setObjectName("checkBox_2")
self.pushButton_ok = QtWidgets.QPushButton(Form)
self.pushButton_ok.setGeometry(QtCore.QRect(90, 200, 71, 31))
self.pushButton_ok.setObjectName("pushButton")
self.pushButton_ok.pressed.connect(self.OK_thread)
self.pushButton_cancel = QtWidgets.QPushButton(Form)
self.pushButton_cancel.setGeometry(QtCore.QRect(210, 200, 71, 31))
self.pushButton_cancel.setObjectName("pushButton_2")
self.pushButton_cancel.clicked.connect(Form.close)
self.retranslateUi(Form)
QtCore.QMetaObject.connectSlotsByName(Form)
def retranslateUi(self, Form):
_translate = QtCore.QCoreApplication.translate
Form.setWindowTitle(_translate("Form", "Form"))
self.checkBox_1.setText(_translate("Form", "Test1"))
self.checkBox_2.setText(_translate("Form", "Test 2"))
self.pushButton.setText(_translate("Form", "OK"))
self.pushButton_2.setText(_translate("Form", "Cancel"))
def OK_thread(self):
global submit_execute_thread
self.pushButton_ok.setEnabled(False)
self.pushButton_cancel.setEnabled(False)
submit_execute_thread = QThread()
submit_execute_thread.started.connect(self.ok_execute)
submit_execute_thread.start()
self.check_execute_thread()
def check_execute_thread(self):
if submit_execute_thread.isRunning() == True:
time.sleep(10)
self.check_execute_thread()
else:
Form.close()
def ok_execute(self):
if self.checkBox_1.isChecked() and self.checkBox_2.ischecked():
self.list_result = ["a","b","c","d","e"]
i have 2 issue here:
My objective is click the File --> Open and 2nd window appear, when i tick the checkbox1 and checkbox2 and press ok_button, i connect the ok_button to OK_thread and make a Qthread to ok_execute function to prevent freezing while running the function and keep checking the thread every 10 seconds until it run finish and close the Form window. I am not sure what is the issue here as it could not work, my GUI still freezing after i press OK_button and never run finish.
passing value:
i try to define the list = [] in def init() in both main window and 2nd window but some variable become not declarable such as "Form", so when i open the Form window from main window, it could not work. and another issue is how do i pass the value from Form window which is from ok_execute return self.list_result to Mainwindow, so when i click the result button in Main Window, it will show the list_result in the listview widget.
Please help me modify the code and appreciate your help.
Thank you.
Regards,
cstung89
I want to print some text and image designed by qtdesigner.
How could I change font and another format in QTextDocument?
from PyQt5 import QtCore, QtGui, QtWidgets, QtPrintSupport
class Ui_MainWindow(object):
def handlePrint(self):
dialog = QtPrintSupport.QPrintDialog()
if dialog.exec_() == QtWidgets.QDialog.Accepted:
self.handlePaintRequest(dialog.printer())
def handlePreview(self):
dialog = QtPrintSupport.QPrintPreviewDialog()
dialog.paintRequested.connect(self.handlePaintRequest)
dialog.exec_()
def handlePaintRequest(self, printer):
document = QtGui.QTextDocument()
cursor = QtGui.QTextCursor(document)
cursor.insertImage('logo4.jpg')
cursor.insertBlock()
cursor.insertText('MY TEXT')
document.print_(printer)
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(800, 600)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.pushButton_print_previw = QtWidgets.QPushButton(self.centralwidget)
self.pushButton_print_previw.setGeometry(QtCore.QRect(90, 270, 251, 91))
font = QtGui.QFont()
font.setPointSize(15)
self.pushButton_print_previw.setFont(font)
self.pushButton_print_previw.setObjectName("pushButton_print_previw")
self.pushButton_print = QtWidgets.QPushButton(self.centralwidget)
self.pushButton_print.setGeometry(QtCore.QRect(440, 270, 251, 91))
font = QtGui.QFont()
font.setPointSize(15)
self.pushButton_print.setFont(font)
self.pushButton_print.setObjectName("pushButton_print")
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 26))
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)
############################################################
self.pushButton_print_previw.clicked.connect(self.handlePreview)
############################################################
############################################################
self.pushButton_print.clicked.connect(self.handlePrint)
############################################################
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.pushButton_print_previw.setText(_translate("MainWindow", "Print Preview"))
self.pushButton_print.setText(_translate("MainWindow", "Print"))
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_())
document.print_(printer) is very convenient but it is not a little flexible.
Because you don't use QTextEdit, you must edit the format information by your code only. (except for setHtml in advance.)
If you draw QPrinter document as you like, you can use QPainter.
Normarly, although QPainter is used in paintEvent(self, event), only if you set a subclass of QPaintDevice to constructor of QPainter, you can draw as you like.
But you must calculate the allocation exactly.
QPrinter is a subclass of QPaintDevice.
Trap
The topleft of QPainter.drawText is the bottom line of Text.
(x, y)→ MY TEXT
Here is the code.
# -*- coding: utf-8 -*-
from PyQt5 import QtCore, QtGui, QtWidgets, QtPrintSupport
class Ui_MainWindow(object):
def handlePrint(self):
dialog = QtPrintSupport.QPrintDialog()
if dialog.exec_() == QtWidgets.QDialog.Accepted:
self.handlePaintRequest(dialog.printer())
def handlePreview(self):
dialog = QtPrintSupport.QPrintPreviewDialog()
dialog.paintRequested.connect(self.handlePaintRequest)
dialog.exec_()
def handlePaintRequest(self, printer):
document = QtGui.QTextDocument()
# cursor = QtGui.QTextCursor(document)
# cursor.insertImage('logo4.jpg')
# cursor.insertBlock()
# cursor.insertText('MY TEXT')
# document.print_(printer)
documentRootFrameFormat = document.rootFrame().frameFormat()
documentLeftMargin = documentRootFrameFormat.leftMargin()
documentTopMargin = documentRootFrameFormat.topMargin()
drawn_im = QtGui.QImage("logo4.jpg")
drawn_im_height = drawn_im.height()
painter = QtGui.QPainter(printer)
painter.drawImage(documentLeftMargin, documentTopMargin, drawn_im)
painter_font = painter.font()
#you can set flag which font is used.
custom_font = QtGui.QFont("Segoe UI Light", 18)
fontMetricsF = QtGui.QFontMetricsF(custom_font)
painter.save()
painter.setFont(custom_font)
height_fontMetricsF = fontMetricsF.height()
painter.drawText(documentLeftMargin, documentTopMargin + drawn_im_height + height_fontMetricsF, 'MY TEXT')
painter.restore()
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(800, 600)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.pushButton_print_previw = QtWidgets.QPushButton(self.centralwidget)
self.pushButton_print_previw.setGeometry(QtCore.QRect(90, 270, 251, 91))
font = QtGui.QFont()
font.setPointSize(15)
self.pushButton_print_previw.setFont(font)
self.pushButton_print_previw.setObjectName("pushButton_print_previw")
self.pushButton_print = QtWidgets.QPushButton(self.centralwidget)
self.pushButton_print.setGeometry(QtCore.QRect(440, 270, 251, 91))
font = QtGui.QFont()
font.setPointSize(15)
self.pushButton_print.setFont(font)
self.pushButton_print.setObjectName("pushButton_print")
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 26))
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)
############################################################
self.pushButton_print_previw.clicked.connect(self.handlePreview)
############################################################
############################################################
self.pushButton_print.clicked.connect(self.handlePrint)
############################################################
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.pushButton_print_previw.setText(_translate("MainWindow", "Print Preview"))
self.pushButton_print.setText(_translate("MainWindow", "Print"))
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_())
My Result
If you want to use QTextCursor, you can set Font & format by using the method of QTextCursor.
You can get the similar result by this code.
I recommend this if you don't hope high control.
Other Solution
def handlePaintRequest(self, printer):
document = QtGui.QTextDocument()
cursor = QtGui.QTextCursor(document)
cursor.insertImage("logo4.jpg")
cursor.insertBlock()
charFormat = cursor.charFormat()
charFormat.setFont(QtGui.QFont("Segoe UI Light", 18))
cursor.insertText('MY TEXT', charFormat)
document.print_(printer)
I have a question in pyqt5. I want to make a Videoplayer. now I'm stuck that how can I gave them complete path it not to click on the button and go to path and select the video I just want that it this one file path. Please have a look to my code. I making this for both raspberry pi and window
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_VideoWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(733, 505)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.Video_Widget = QVideoWidget(self.centralwidget)
self.Video_Widget.setGeometry(QtCore.QRect(0, 0, 711, 361))
self.Video_Widget.setObjectName("Video_Widget")
self.horizontalScrollBar = QtWidgets.QScrollBar(self.centralwidget)
self.horizontalScrollBar.setGeometry(QtCore.QRect(0, 380, 721, 16))
self.horizontalScrollBar.setOrientation(QtCore.Qt.Horizontal)
self.horizontalScrollBar.setObjectName("horizontalScrollBar")
self.play = QtWidgets.QPushButton(self.centralwidget)
self.play.setGeometry(QtCore.QRect(10, 410, 75, 23))
self.play.setObjectName("play")
self.select = QtWidgets.QPushButton(self.centralwidget)
self.select.setGeometry(QtCore.QRect(550, 410, 75, 23))
self.select.setObjectName("select")
self.play.clicked.connect(self.load_video)
MainWindow.setCentralWidget(self.centralwidget)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def load_video(self):
filepath = 'F:/Fun/Songs/12.mp4'
self.Video_Widget.load(filepath)
self.horizontalScrollBar.setMediaObject(self.Video_Widget.mediaObject())
self.Video_Widget.play()
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.play.setText(_translate("MainWindow", "play"))
self.select.setText(_translate("MainWindow", "Select"))
from PyQt5.QtMultimediaWidgets import QVideoWidget
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = Ui_VideoWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
I used this code too which is present in official documentation.
def load_video(self):
player = QMediaPlayer()
playlist = QMediaPlaylist(player)
playlist.addMedia(QUrl('F:/Fun/Songs/12.mp4'))
player.setVideoOutput(self.Video_Widget)
self.Video_Widget.show()
playlist.setCurrentIndex(1)
player.play()
while using this code which is in official documentation. this error occurred.
As the error and the docs point out, a QMediaContent must be passed to the addMedia method. To build a QMediaContent you can use a QUrl:
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_VideoWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(733, 505)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.Video_Widget = QVideoWidget(self.centralwidget)
self.Video_Widget.setGeometry(QtCore.QRect(0, 0, 711, 361))
self.Video_Widget.setObjectName("Video_Widget")
self.horizontalScrollBar = QtWidgets.QScrollBar(self.centralwidget)
self.horizontalScrollBar.setGeometry(QtCore.QRect(0, 380, 721, 16))
self.horizontalScrollBar.setOrientation(QtCore.Qt.Horizontal)
self.horizontalScrollBar.setObjectName("horizontalScrollBar")
self.play = QtWidgets.QPushButton(self.centralwidget)
self.play.setGeometry(QtCore.QRect(10, 410, 75, 23))
self.play.setObjectName("play")
self.select = QtWidgets.QPushButton(self.centralwidget)
self.select.setGeometry(QtCore.QRect(550, 410, 75, 23))
self.select.setObjectName("select")
MainWindow.setCentralWidget(self.centralwidget)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.play.setText(_translate("MainWindow", "play"))
self.select.setText(_translate("MainWindow", "Select"))
from PyQt5.QtMultimediaWidgets import QVideoWidget
from PyQt5 import QtMultimedia
class VideoWindow(QtWidgets.QMainWindow, Ui_VideoWindow):
def __init__(self, parent=None):
super(VideoWindow, self).__init__(parent)
self.setupUi(self)
self.player = QtMultimedia.QMediaPlayer(self)
self.player.setVideoOutput(self.Video_Widget)
self.play.clicked.connect(self.player.play)
self.playlist = QtMultimedia.QMediaPlaylist(self.player)
self.player.setPlaylist(self.playlist)
self.playlist.addMedia(
QtMultimedia.QMediaContent(QtCore.QUrl.fromLocalFile("F:/Fun/Songs/12.mp4"))
)
self.playlist.setCurrentIndex(0)
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
w = VideoWindow()
w.show()
sys.exit(app.exec_())
I have two windows, first window is 'FirstWindow' and second is 'Calendar'. first window has one push button (pbSelectDate) and one label (lbDate). calendar window has calendar (CalendarBox) and one push button (pbSelect).
when i click select (pbSelectDate) from first window, calendar window pops up. I select the date and press select button (pbSelect) in the calendar window. i want to print the selected date to the label (lbDate) in the first window.
thanks in advance. :)
this is the first window script.
from PyQt5 import QtCore, QtGui, QtWidgets
from Calendar import Ui_CalendarWindow
class Ui_FirstWindow(object):
def Open_Calendar(self):
self.window = QtWidgets.QMainWindow()
self.ui = Ui_CalendarWindow()
self.ui.setupUi(self.window)
self.window.show()
def setupUi(self, FirstWindow):
FirstWindow.setObjectName("FirstWindow")
FirstWindow.resize(654, 242)
self.centralwidget = QtWidgets.QWidget(FirstWindow)
self.centralwidget.setObjectName("centralwidget")
self.lbDate = QtWidgets.QLabel(self.centralwidget)
self.lbDate.setGeometry(QtCore.QRect(330, 70, 281, 131))
font = QtGui.QFont()
font.setPointSize(16)
font.setBold(True)
font.setWeight(75)
self.lbDate.setFont(font)
self.lbDate.setLayoutDirection(QtCore.Qt.LeftToRight)
self.lbDate.setObjectName("lbDate")
self.pbSelectDate = QtWidgets.QPushButton(self.centralwidget)
self.pbSelectDate.setGeometry(QtCore.QRect(80, 100, 191, 61))
self.pbSelectDate.setObjectName("pbSelectDate")
self.pbSelectDate.clicked.connect(self.Open_Calendar)
FirstWindow.setCentralWidget(self.centralwidget)
self.statusbar = QtWidgets.QStatusBar(FirstWindow)
self.statusbar.setObjectName("statusbar")
FirstWindow.setStatusBar(self.statusbar)
self.retranslateUi(FirstWindow)
QtCore.QMetaObject.connectSlotsByName(FirstWindow)
def retranslateUi(self, FirstWindow):
_translate = QtCore.QCoreApplication.translate
FirstWindow.setWindowTitle(_translate("FirstWindow", "MainWindow"))
self.lbDate.setText(_translate("FirstWindow", "Sep"))
self.pbSelectDate.setText(_translate("FirstWindow", "Select Date"))
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
FirstWindow = QtWidgets.QMainWindow()
ui = Ui_FirstWindow()
ui.setupUi(FirstWindow)
FirstWindow.show()
sys.exit(app.exec_())
this is the Calendar window script..
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_CalendarWindow(object):
def PickedDate(self,var):
self.selecteddate = self.CalendarBox.selectedDate()
#print(self.selecteddate.toString('MMM')+'-'+self.selecteddate.toString('yyyy'))
def setupUi(self, CalendarWindow):
CalendarWindow.setObjectName("CalendarWindow")
CalendarWindow.resize(512, 458)
self.centralwidget = QtWidgets.QWidget(CalendarWindow)
self.centralwidget.setObjectName("centralwidget")
self.CalendarBox = QtWidgets.QCalendarWidget(self.centralwidget)
self.CalendarBox.setGeometry(QtCore.QRect(20, 20, 464, 289))
self.CalendarBox.setObjectName("CalendarBox")
self.pbSelect = QtWidgets.QPushButton(self.centralwidget)
self.pbSelect.setGeometry(QtCore.QRect(160, 330, 181, 60))
font = QtGui.QFont()
font.setPointSize(10)
font.setBold(True)
font.setWeight(75)
self.pbSelect.setFont(font)
self.pbSelect.setObjectName("pbSelect")
self.pbSelect.clicked.connect(self.PickedDate)
CalendarWindow.setCentralWidget(self.centralwidget)
self.statusbar = QtWidgets.QStatusBar(CalendarWindow)
self.statusbar.setObjectName("statusbar")
CalendarWindow.setStatusBar(self.statusbar)
self.retranslateUi(CalendarWindow)
QtCore.QMetaObject.connectSlotsByName(CalendarWindow)
def retranslateUi(self, CalendarWindow):
_translate = QtCore.QCoreApplication.translate
CalendarWindow.setWindowTitle(_translate("CalendarWindow", "MainWindow"))
self.pbSelect.setText(_translate("CalendarWindow", "Select"))
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
CalendarWindow = QtWidgets.QMainWindow()
ui = Ui_CalendarWindow()
ui.setupUi(CalendarWindow)
CalendarWindow.show()
sys.exit(app.exec_())
Do not modify the code generated by Qt Designer but create another class that inherits from the appropriate widget and use the initial class to fill it.
QLabel.setText(const QString )
Setting the text clears any previous content.
from PyQt5 import QtCore, QtGui, QtWidgets
#from Calendar import Ui_CalendarWindow
class Ui_CalendarWindow(object):
def setupUi(self, CalendarWindow):
CalendarWindow.setObjectName("CalendarWindow")
CalendarWindow.resize(512, 458)
self.centralwidget = QtWidgets.QWidget(CalendarWindow)
self.centralwidget.setObjectName("centralwidget")
self.CalendarBox = QtWidgets.QCalendarWidget(self.centralwidget)
self.CalendarBox.setGeometry(QtCore.QRect(20, 20, 464, 289))
self.CalendarBox.setObjectName("CalendarBox")
self.pbSelect = QtWidgets.QPushButton(self.centralwidget)
self.pbSelect.setGeometry(QtCore.QRect(160, 330, 181, 60))
font = QtGui.QFont()
font.setPointSize(10)
font.setBold(True)
font.setWeight(75)
self.pbSelect.setFont(font)
self.pbSelect.setObjectName("pbSelect")
# self.pbSelect.clicked.connect(self.PickedDate)
CalendarWindow.setCentralWidget(self.centralwidget)
self.statusbar = QtWidgets.QStatusBar(CalendarWindow)
self.statusbar.setObjectName("statusbar")
CalendarWindow.setStatusBar(self.statusbar)
self.retranslateUi(CalendarWindow)
QtCore.QMetaObject.connectSlotsByName(CalendarWindow)
def retranslateUi(self, CalendarWindow):
_translate = QtCore.QCoreApplication.translate
CalendarWindow.setWindowTitle(_translate("CalendarWindow", "MainWindow"))
self.pbSelect.setText(_translate("CalendarWindow", "Select"))
class Ui_FirstWindow(object):
def setupUi(self, FirstWindow):
FirstWindow.setObjectName("FirstWindow")
FirstWindow.resize(654, 242)
self.centralwidget = QtWidgets.QWidget(FirstWindow)
self.centralwidget.setObjectName("centralwidget")
self.lbDate = QtWidgets.QLabel(self.centralwidget)
self.lbDate.setGeometry(QtCore.QRect(330, 70, 281, 131))
font = QtGui.QFont()
font.setPointSize(16)
font.setBold(True)
font.setWeight(75)
self.lbDate.setFont(font)
self.lbDate.setLayoutDirection(QtCore.Qt.LeftToRight)
self.lbDate.setObjectName("lbDate")
self.pbSelectDate = QtWidgets.QPushButton(self.centralwidget)
self.pbSelectDate.setGeometry(QtCore.QRect(80, 100, 191, 61))
self.pbSelectDate.setObjectName("pbSelectDate")
# self.pbSelectDate.clicked.connect(self.Open_Calendar)
FirstWindow.setCentralWidget(self.centralwidget)
self.statusbar = QtWidgets.QStatusBar(FirstWindow)
self.statusbar.setObjectName("statusbar")
FirstWindow.setStatusBar(self.statusbar)
self.retranslateUi(FirstWindow)
QtCore.QMetaObject.connectSlotsByName(FirstWindow)
def retranslateUi(self, FirstWindow):
_translate = QtCore.QCoreApplication.translate
FirstWindow.setWindowTitle(_translate("FirstWindow", "MainWindow"))
self.lbDate.setText(_translate("FirstWindow", "Sep"))
self.pbSelectDate.setText(_translate("FirstWindow", "Select Date"))
class CalendarWindow(QtWidgets.QMainWindow, Ui_CalendarWindow): # +
def __init__(self):
super(CalendarWindow, self).__init__()
self.setupUi(self)
class FirstWindow(QtWidgets.QMainWindow, Ui_FirstWindow): # +
def __init__(self):
super(FirstWindow, self).__init__()
self.setupUi(self)
self.pbSelectDate.clicked.connect(self.Open_Calendar)
def Open_Calendar(self):
self.window = CalendarWindow()
self.window.setupUi(self.window)
self.window.show()
self.window.pbSelect.clicked.connect(self.PickedDate)
def PickedDate(self): # , var
self.selecteddate = self.window.CalendarBox.selectedDate()
# print(self.selecteddate.toString('MMM')+'-'+self.selecteddate.toString('yyyy'))
self.lbDate.setText(self.selecteddate.toString('ddd-MMM-yyyy')) # <---
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
w = FirstWindow()
w.show()
sys.exit(app.exec_())