paintEvent() for a specific Widget - python

This example draws an ellipse in the main window. I would like to draw the ellipse in the secondary window as soon as I click the pushbutton in the main window. This, however, without having to create another class. I tried but I can't.
Another question: Is it possible to insert a geometric figure in a Box Layout?
#!/usr/bin/python3.6
# -*- coding: utf-8 -*-
import sys
from PyQt5.QtWidgets import QMainWindow, QApplication, QPushButton, QDialog
from PyQt5 import QtGui
from PyQt5.QtGui import QPainter,QBrush,QPen
from PyQt5 import QtCore
class Window(QMainWindow):
def __init__(self):
super().__init__()
title = "Main Window";left=100;top=100;width=1200;height=800
self.setWindowTitle(title)
self.setGeometry(left,top,width,height)
self.Create_Button()
self.show()
def Create_Button(self):
button = QPushButton("Click", self)
button.setGeometry(30,100,200,80)
button.clicked.connect(self.SecondWin)
def paintEvent(self,event):
painter = QPainter(self)
painter.setPen(QPen(QtCore.Qt.red,6,QtCore.Qt.SolidLine))
painter.setBrush(QBrush(QtGui.QColor(45,171,200),QtCore.Qt.SolidPattern))
painter.drawEllipse(550,150,300,600)
def SecondWin(self,event):
mydialog = QDialog(self)
mydialog.setWindowTitle("Second Window")
mydialog.setGeometry(400,200,600,300)
mydialog.show()
App = QApplication(sys.argv)
window = Window()
sys.exit(App.exec_())

Related

PyVista Plotter in QFrame doesn't fill the full frame

I want to make a GUI with QtDesigner.
There is a QFrame for the PyVista plot but the plot doesn't fill the full frame.
Here is my code:
from PySide6.QtWidgets import QApplication, QMainWindow
from QT_Designer.Validation import Ui_MainWindow
from pyvistaqt import QtInteractor, MainWindow
class Frm_main(QMainWindow, Ui_MainWindow):
def __init__(self):
super().__init__()
self.setupUi(self)
# Window (Plotter or Frame)
self.plotter = QtInteractor(self.f_window)
I tried to set the plotter to full_screen or change the layout of the frame but neither fixes the issue.
I looked at a view examples and find now a solution:
from PySide6.QtWidgets import QApplication, QMainWindow, QVBoxLayout
from QT_Designer.Validation import Ui_MainWindow
from pyvistaqt import QtInteractor, MainWindow
class Frm_main(QMainWindow, Ui_MainWindow):
def __init__(self):
super().__init__()
self.setupUi(self)
vlayout = QVBoxLayout()
# Window (Plotter or Frame)
self.plotter = QtInteractor(self.f_window)
vlayout.addWidget(self.plotter.interactor)
self.f_window.setLayout(vlayout)
Now the plotter is in the full frame :)

Switching ui without new window PyQT5

I want to change the UI without opening new windows. The problem is that when I do this on widgets then the app is not frameless. When I do it without widgets I have no idea how to change the UI.
Without widget
import sys, time, os
from PyQt5 import uic
from PyQt5 import QtWidgets, QtCore, QtGui
from PyQt5.QtWidgets import *
from PyQt5.QtGui import QPixmap
import sqlite3
class LoginMenu(QWidget):
def __init__(self):
super(LoginMenu, self).__init__()
self.setWindowFlags(QtCore.Qt.FramelessWindowHint)
uic.loadUi("LoginMenu.ui",self)
self.clicked = False
def mousePressEvent(self, event):
self.old_pos = event.screenPos()
def mouseMoveEvent(self, event):
if self.clicked:
dx = self.old_pos.x() - event.screenPos().x()
dy = self.old_pos.y() - event.screenPos().y()
self.move(self.pos().x() - dx, self.pos().y() - dy)
self.old_pos = event.screenPos()
self.clicked = True
return QWidget.mouseMoveEvent(self, event)
app = QApplication(sys.argv)
log = LoginMenu()
log.show()
sys.exit(app.exec())
with widgets to run app
import sys, time, os
from PyQt5 import uic
from PyQt5 import QtWidgets, QtCore, QtGui
from PyQt5.QtWidgets import *
from PyQt5.QtGui import QPixmap
class LogMenu(QWidget):
def __init__(self):
super(LogMenu, self).__init__()
uic.loadUi("LoginMenu.ui",self)
self.SignUp.clicked.connect(self.gotoReg)
def gotoReg(self):
reg=Register()
widget.addWidget(reg)
widget.setCurrentIndex(widget.currentIndex()+1)
class Register(QWidget):
def __init__(self):
super(Register, self).__init__()
uic.loadUi("SignUp.ui",self)
#main
app = QApplication(sys.argv)
widget = QtWidgets.QStackedWidget()
log=LogMenu()
reg=Register()
widget.addWidget(log)
widget.addWidget(reg)
widget.show()
try:
sys.exit(app.exec())
except:
print("Exiting")
sry for my eng if sth i wrote sth bad
tbh idk how to make it frameless with widgets and draggable with clicking and holding the app or switchable without using widget to run it

How to get size of widgets

I am developing a PyQt5 application however I am having issues with the heights of the widgets. Below is a simplified version of my issue:
import sys
from PyQt5.QtWidgets import *
from PyQt5.QtWebEngineWidgets import QWebEngineView
from PyQt5.QtCore import *
from PyQt5.QtGui import *
class App(QWidget):
def __init__(self):
super().__init__()
self.showMaximized()
self.setStyleSheet("QWidget {background: blue;}")
print(self.frameGeometry().height())
self.show()
if __name__ == "__main__":
window = QApplication(sys.argv)
app = App()
window.setStyle(QStyleFactory.create("Fusion"))
window.exec_()
Here I create a window and maximise it. Using a tkinter window, it tells me the height maximised is 841, which is the size of my screen, however the PyQt5 application prints the height to be 519. Is this an issue with the self.showMaximized() method, or some other issue.
Resizing is not instantaneous in Qt. What Qt does is take the information from showMaximized to activate the flag of the native window (library that depends on each OS) then after a time T the OS applies that flag and sends it the new geometry. So in your case you have to give it a delay to get the correct information.
import sys
from PyQt5.QtWidgets import QApplication, QStyleFactory, QWidget
from PyQt5.QtCore import QTimer
class App(QWidget):
def __init__(self):
super().__init__()
self.setStyleSheet("QWidget {background: blue;}")
self.showMaximized()
QTimer.singleShot(100, self.calculate)
def calculate(self):
print(self.frameGeometry().height())
if __name__ == "__main__":
window = QApplication(sys.argv)
app = App()
window.setStyle(QStyleFactory.create("Fusion"))
window.exec_()
On the other hand, if your objective is to know the size of the initial screen then you should not use a QWidget for that since it will depend on the time it takes for Qt and the native library to create the native window, instead use the Screen class :
import sys
from PyQt5.QtWidgets import QApplication
from PyQt5.QtGui import QGuiApplication
if __name__ == "__main__":
window = QApplication(sys.argv)
print(QGuiApplication.primaryScreen().availableGeometry().height())

How to align QPlainTextEdit to right?

I want to write a notepad in python with PyQt5 for persian language.
how can I align the thext in QPlainTextEdit to right?
this is my code:
from PyQt5.QtWidgets import QApplication, QMainWindow, QPlainTextEdit
from PyQt5.QtCore import Qt, QLocale
class TextBox(QPlainTextEdit):
def persian(self):
self.setFixedSize(640, 480)
self.setLayoutDirection(Qt.RightToLeft)
self.setLocale(QLocale(QLocale.Persian, QLocale.Iran))
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.GUI()
def GUI(self):
self.setWindowTitle("My title")
self.setFixedSize(640, 480)
self.text = TextBox(self)
self.text.persian()
app = QApplication([])
window = MainWindow()
window.show()
app.exec_()
You can use a QTextEdit instead of QPlainTextEdit and use setAlignment(Qt.AlignRight), e.g.
from PyQt5.QtWidgets import QTextEdit
from PyQt5.QtCore import Qt
class TextBox(QTextEdit):
def persian(self):
self.setFixedSize(640, 480)
self.setLayoutDirection(Qt.RightToLeft)
self.setLocale(QLocale(QLocale.Persian, QLocale.Iran))
# set text alignment to AlignRight
self.setAlignment(Qt.AlignRight)

Create Splash screen in PyQt5

I want to create a splash screen in PyQt5 using Python. I searched but I found in Pyqt4 and I have no understanding of PyQt4 so help me in this case I would be gratful
Splash screen in pyqt
I like to add it in just before i load my main widget with a slight fade - note this is only useful to show a logo, if your application has a long load time you can utilise the splash screen like #S. Nick has shown to allow load time whilst you show the splashscreen:
from PyQt5 import QtGui, QtCore, QtWidgets
import time
if __name__ == '__main__':
app = QtWidgets.QApplication([])
# Create splashscreen
splash_pix = QtGui.QPixmap('picture.png')
splash = QtWidgets.QSplashScreen(splash_pix, QtCore.Qt.WindowStaysOnTopHint)
# add fade to splashscreen
opaqueness = 0.0
step = 0.1
splash.setWindowOpacity(opaqueness)
splash.show()
while opaqueness < 1:
splash.setWindowOpacity(opaqueness)
time.sleep(step) # Gradually appears
opaqueness+=step
time.sleep(1) # hold image on screen for a while
splash.close() # close the splash screen
#widget = YourWidget()
#widget.show() # This is where you'd run the normal application
app.exec_()
Try it:
import sys
from PyQt5.QtGui import QPixmap
from PyQt5.QtWidgets import QDialog, QPushButton, QVBoxLayout, QApplication, QSplashScreen
from PyQt5.QtCore import QTimer
class Dialog(QDialog):
def __init__(self, parent=None):
super(Dialog, self).__init__(parent)
self.b1 = QPushButton('Display screensaver')
self.b1.clicked.connect(self.flashSplash)
layout = QVBoxLayout()
self.setLayout(layout)
layout.addWidget(self.b1)
def flashSplash(self):
self.splash = QSplashScreen(QPixmap('D:/_Qt/img/pyqt.jpg'))
# By default, SplashScreen will be in the center of the screen.
# You can move it to a specific location if you want:
# self.splash.move(10,10)
self.splash.show()
# Close SplashScreen after 2 seconds (2000 ms)
QTimer.singleShot(2000, self.splash.close)
if __name__ == '__main__':
app = QApplication(sys.argv)
main = Dialog()
main.show()
sys.exit(app.exec_())
Example 2
import sys
from PyQt5 import QtCore, QtGui, QtWidgets # + QtWidgets
import sys
from PyQt5.QtWidgets import QApplication, QLabel
from PyQt5.QtCore import QTimer, Qt
if __name__ == '__main__':
app = QApplication(sys.argv)
label = QLabel("""
<font color=red size=128>
<b>Hello PyQt, The window will disappear after 5 seconds!</b>
</font>""")
# SplashScreen - Indicates that the window is a splash screen. This is the default type for .QSplashScreen
# FramelessWindowHint - Creates a borderless window. The user cannot move or resize the borderless window through the window system.
label.setWindowFlags(Qt.SplashScreen | Qt.FramelessWindowHint)
label.show()
# Automatically exit after 5 seconds
QTimer.singleShot(5000, app.quit)
sys.exit(app.exec_())
The simple and best example that I found.
https://www.youtube.com/watch?v=TsatZJfzb_Q&t=162s
from PyQt5.QtWidgets import QMainWindow, QApplication, QDialog
from PyQt5.QtWidgets import QGraphicsScene,QSplashScreen
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QPixmap
class SplashScreen(QSplashScreen):
def __init__(self):
super(QSplashScreen, self).__init__()
loadUi("splash.ui", self)
self.setWindowFlag(Qt.FramelessWindowHint)
pixmap = QPixmap("any_image.jpg")
self.setPixmap(pixmap)
def progress(self):
for i in range(40):
time.sleep(0.1)
self.progressBar.setValue(i)
class MainScreen(QMainWindow):
def function1():
.......
def function2():
......
if __name__ == "__main__":
app = QApplication(sys.argv)
splash = SplashScreen()
splash.show()
splash.progress()
mainscreen = MainScreen()
mainscreen.show()
splash.finish(widget)
sys.exit(app.exec_())

Categories