import sys
from PyQt5.QtWidgets import QWidget, QVBoxLayout, QLabel, QApplication
class Example(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.setGeometry(300, 200, 600, 400)
self.setWindowTitle('Пример')
hbox_layout = QVBoxLayout()
red_widget = QWidget()
red_widget.setStyleSheet("background: green;")
green_widget = QWidget()
green_widget.setStyleSheet("background: green;")
hbox_layout.addWidget(red_widget)
hbox_layout.addWidget(green_widget)
self.setLayout(hbox_layout)
transparent_widget = QWidget(self)
transparent_widget.setGeometry(0, 0, 600, 400)
transparent_widget.setStyleSheet("background-color: rgba(117, 190, 218, 0.4);")
if __name__ == '__main__':
app = QApplication(sys.argv)
example = Example()
example.show()
sys.exit(app.exec_())
import sys
from PyQt5.QtWidgets import *
class Example(QWidget):
def __init__(self):
super().__init__()
self.setWindowTitle("Пример")
self.grid_layout = QGridLayout()
self.setLayout(self.grid_layout)
self.textEdit = QTextEdit(self)
self.textEdit.toPlainText()
self.pushButton = QPushButton('ok', self)
self.pushButton.move(50, 50)
self.pushButton.clicked.connect(self.pushButtonClickedHandler)
self.grid_layout.addWidget(self.textEdit, 0, 0)
self.grid_layout.addWidget(self.pushButton)
def pushButtonClickedHandler(self):
text = self.textEdit.toPlainText()
self.grid_layout.addWidget(QLabel(text = text))
if __name__ == '__main__':
app = QApplication(sys.argv)
form = Example()
form.show()
app.exec()
import os
import sys
from io import BytesIO
from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout
from PyQt5.QtWidgets import QLabel, QPushButton, QMessageBox
from PyQt5.QtGui import QPixmap, QImage
import requests
url = """https://3.bp.blogspot.com/-rDqzMGTOAzI/U0Uj\
-HQauwI/AAAAAAAAB1c/4YfKMvqN_wk/s1600/%D0%94%D0%B0%D0\
%B2%D0%B0%D0%B9+%D1%8F+%D0%BF%D0%BE%D0%B8%D1%89%D1%83+\
%D0%B2+Google+%D0%B7%D0%B0+%D1%82%D0%B5%D0%B1%D1%8F.png
"""
# Отловить ошибки в слотах PyQt5
def log_uncaught_exceptions(ex_cls, ex, tb):
text = '{}: {}:\n'.format(ex_cls.__name__, ex)
import traceback
text += ''.join(traceback.format_tb(tb))
print(text)
QMessageBox.critical(None, 'Упс( Ошибочка...', text)
quit()
sys.excepthook = log_uncaught_exceptions
class WindowsApplication(QWidget):
def __init__(self):
super().__init__()
self.setWindowTitle('Супер приложение')
self.setGeometry(300, 200, 800, 600)
vbox = QVBoxLayout(self)
label = QLabel()
button = QPushButton(text='Сделать снимок приложения')
button.clicked.connect(self.buttonHandler)
vbox.addWidget(label)
vbox.addWidget(button)
content = requests.get(url).content
pixmap = QPixmap()
pixmap.loadFromData(content)
label.setPixmap(pixmap)
def buttonHandler(self):
grab = self.grab()
grab.save('image.png', 'png')
os.startfile('image.png')
print('END')
def main():
application = QApplication(sys.argv)
main_window = WindowsApplication()
main_window.show()
sys.exit(application.exec_())
if __name__ == '__main__':
main()
def log_uncaught_exceptions(ex_cls, ex, tb):
text = '{}: {}:\n'.format(ex_cls.__name__, ex)
import traceback
text += ''.join(traceback.format_tb(tb))
print(text)
QtWidgets.QMessageBox.critical(None, 'Error', text)
quit()
sys.excepthook = log_uncaught_exceptions
И да будет вам счастье
import sys
from PyQt5.QtWidgets import *
def log_uncaught_exceptions(ex_cls, ex, tb):
text = '{}: {}:\n'.format(ex_cls.__name__, ex)
import traceback
text += ''.join(traceback.format_tb(tb))
print(text)
QMessageBox.critical(None, 'Error', text)
quit()
sys.excepthook = log_uncaught_exceptions
class MainWindow(QWidget):
def __init__(self):
super().__init__()
self.setWindowTitle('Передача значения из QLineEdit в QListWidget')
self.setGeometry(300, 300, 500, 400)
vbox = QVBoxLayout(self)
self.line_edit = QLineEdit()
self.list_widget = QListWidget()
self.button = QPushButton('Запустить')
self.button.clicked.connect(self.add_item)
vbox.addWidget(self.line_edit)
vbox.addWidget(self.list_widget)
vbox.addWidget(self.button)
def add_item(self):
self.list_widget.addItem(self.line_edit.text()) #QLineEdit метод метод text возвращает текст
# По QListWidget читайте документацию
print(self.line_edit.text())
if __name__ == "__main__":
app = QApplication(sys.argv)
main = MainWindow()
main.show()
sys.exit(app.exec_())
import sys
from PyQt5.QtWidgets import QWidget, QLabel
from PyQt5.QtGui import QPixmap
from PyQt5.QtWidgets import QApplication
import requests
from bs4 import BeautifulSoup
from nltk.tokenize import RegexpTokenizer
import nltk
import io
nltk.download('stopwords')
from nltk.corpus import stopwords
import matplotlib.pyplot as pyplot
from stop_words import get_stop_words
r = requests.get('https://www.gutenberg.org/files/2701/2701-h/2701-h.htm')
# Извлечение HTML
html = r.text
# Создаём BeautifulSoup из HTML
soup = BeautifulSoup(html, "html5lib")
# Получаем текст
text = soup.get_text()
# Создаём tokenizer, выкидывая знаки пунктуации
tokenizer = RegexpTokenizer('\w+')
# Создаём tokens
tokens = tokenizer.tokenize(text)
# Создаем новый list
words = []
# Перебираем список
for word in tokens:
words.append(word.lower())
# Получаем английские стоп-слова и выводим некоторые из них
sw = nltk.corpus.stopwords.words('english')
with io.open("STOP_EN.txt", "r", encoding='utf-8') as myfile:
data = myfile.read().splitlines()
sw.extend(data)
data2 = get_stop_words('en')
sw.extend(data2)
# Создаем новый list
words_ns = []
for word in words:
if word not in sw:
words_ns.append(word)
# создаем график плотности ключевых слов
fd = nltk.FreqDist(words_ns)
total = fd.N()
for wordo in fd:
fd[wordo] /= float(total)/100
fd.plot(25)
pyplot.savefig("image.png")
class ImageViewer(QWidget):
def __init__(self):
super().__init__()
image_label = QLabel(self)
pixmap = QPixmap("image.png")
image_label.setPixmap(pixmap)
self.resize(pixmap.width(), pixmap.height()) # fit window to the image
self.setWindowTitle('График функции')
def main():
app = QApplication(sys.argv)
image_viewer = ImageViewer()
image_viewer.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
import sys
from PySide2.QtCore import *
from PySide2.QtGui import *
from PySide2.QtWidgets import *
import cv2 # OpenCV
import qimage2ndarray # for a memory leak
class ThreadCamera(QThread):
status = True
changePixmap = Signal(QImage)
def __init__(self):
super().__init__()
self.capture = cv2.VideoCapture(0)
def setStatus(self, status):
self.status = status
def captureRelease(self):
self.capture.release()
def run(self):
while self.status:
face_cascade = cv2.CascadeClassifier(r'haarcascade_frontalface_default.xml')
ret, frame = self.capture.read()
if (ret == True):
self.capture.set(3,640)
self.capture.set(4, 480)
frame = cv2.cvtColor (frame, cv2.COLOR_BGR2RGB)
gray = cv2.cvtColor (frame, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
for (x,y,w,h) in faces:
frame = cv2.rectangle(frame,(x,y),(x+w,y+h),(255,0,0),2)
roi_gray = gray[y:y+h, x:x+w]
roi_color = frame[y:y+h, x:x+w]
image = qimage2ndarray.array2qimage(frame)
self.changePixmap.emit(image)
class ThreadVideoFile(QThread):
status = True
changePixmap = Signal(QImage)
def __init__(self, path):
super().__init__()
self.capture = cv2.VideoCapture(path)
def set_status(self, status):
self.status = status
def captureRelease(self):
self.capture.release()
def run(self):
while self.status:
face_cascade = cv2.CascadeClassifier(r'haarcascade_frontalface_default.xml')
ret, frame = self.capture.read()
if (ret == True):
self.capture.set(3,640)
self.capture.set(4, 480)
frame = cv2.cvtColor (frame, cv2.COLOR_BGR2RGB)
gray = cv2.cvtColor (frame, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
for (x,y,w,h) in faces:
frame = cv2.rectangle(frame,(x,y),(x+w,y+h),(255,0,0),2)
roi_gray = gray[y:y+h, x:x+w]
roi_color = frame[y:y+h, x:x+w]
image = qimage2ndarray.array2qimage(frame)
self.changePixmap.emit(image)
class Dialog(QDialog):
def __init__(self, parent):
super().__init__()
self.resize(400, 100)
self.label = QLabel()
self.label.setText("<center><h1>Выберите действие</h1></center>")
self.button_open_camera = QPushButton('Камера')
self.button_open_camera.clicked.connect(parent.open_camera)
self.button_open_file = QPushButton('Видео файл')
self.button_open_file.clicked.connect(parent.open_file)
layout = QVBoxLayout()
layout.addWidget(self.label)
layout.addWidget(self.button_open_camera)
layout.addWidget(self.button_open_file)
self.setLayout(layout)
class VideoWidget(QWidget):
def __init__(self):
super().__init__()
self.initUI()
self.thread_camera = ThreadCamera()
self.thread_video = ThreadVideoFile("videoplayback.mp4")
@Slot(QImage)
def setImage (self, image):
self.label.setPixmap(QPixmap.fromImage(image))
def initUI(self):
self.setFixedSize(640, 480)
self.label = QLabel(self)
self.label.setText("Загрузите видео")
self.label.setAlignment(Qt.AlignCenter)
self.label.installEventFilter(self)
self.layout = QVBoxLayout(self)
self.layout.setContentsMargins(0, 0, 0, 0)
self.layout.addWidget(self.label)
self.setLayout(self.layout)
def eventFilter(self, obj, event):
# Только фильтровать событие label, переписать его поведение,
# другие события будут проигнорированы
if obj == self.label:
# здесь отфильтруйте событие mouse и перепишите его поведение
if event.type() == QEvent.MouseButtonPress:
if event.buttons() == Qt.LeftButton:
self.dialog = Dialog(self)
self.dialog.exec_()
return False
def open_file(self):
if self.thread_video.isRunning() is True:
self.thread_video.set_status(False)
self.thread_video.captureRelease()
self.dialog.hide()
self.thread_camera.setStatus(False)
self.thread_camera.captureRelease()
self.label.setText("Загрузите видео")
fileDialog = QFileDialog(self)
supportedMimeTypes = ["video", "*.*"]
fileDialog.setMimeTypeFilters(supportedMimeTypes)
moviesLocation = QStandardPaths.writableLocation(QStandardPaths.MoviesLocation)
fileDialog.setDirectory(moviesLocation)
if fileDialog.exec_() == QDialog.Accepted:
self.file = fileDialog.selectedUrls()[0].toDisplayString()
self.thread_video = ThreadVideoFile(self.file)
self.thread_video.changePixmap.connect(self.setImage)
self.thread_video.start()
def open_camera(self):
self.dialog.hide()
self.thread_video.set_status(False)
self.thread_video.captureRelease()
self.label.setText("Загрузите видео")
self.thread_camera = ThreadCamera()
self.thread_camera.changePixmap.connect(self.setImage)
self.thread_camera.start()
def main():
app = QApplication([])
video_widget = VideoWidget()
video_widget.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
import sys
from PyQt5.QtWidgets import (QWidget, QApplication, QPushButton, QSlider,
QVBoxLayout, QMessageBox)
from PyQt5.QtCore import Qt
class QButtonExample(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.setGeometry(300, 300, 200, 150)
self.button = QPushButton(self, text="Ты не сможешь на меня нажать!")
self.button.setEnabled(False)
self.button.clicked.connect(self.handleButton)
slider = QSlider(Qt.Horizontal, self)
slider.setFocusPolicy(Qt.NoFocus)
slider.setGeometry(30, 40, 100, 30)
slider.valueChanged[int].connect(self.changeValue)
boxLayout = QVBoxLayout(self)
# boxLayout.addStretch(1)
boxLayout.addWidget(self.button)
boxLayout.addWidget(slider)
def changeValue(self, value):
if value > 50:
self.button.setEnabled(True)
else:
self.button.setEnabled(False)
def handleButton(self):
QMessageBox.information(None, 'Сообщение от программы', "Да ладно! у тебя получилось!")
if __name__ == '__main__':
app = QApplication(sys.argv)
myApplication = QButtonExample()
myApplication.show()
sys.exit(app.exec_())
from io import BytesIO
import requests
from PyQt5.QtWidgets import (QApplication, QMainWindow, QGridLayout,
QWidget, QTableWidget, QTableWidgetItem)
from PyQt5.QtGui import QPixmap, QIcon
from PyQt5.QtCore import QSize, Qt, QThread, pyqtSignal, pyqtSlot
class UploadImage(QThread):
data = pyqtSignal(bytes)
def __init__(self):
super().__init__()
@pyqtSlot()
def run(self):
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.2)\
AppleWebKit/537.36 (KHTML, like Gecko)\
Chrome/63.0.3239.84 Safari/537.36',
'Accept-Language': 'ru-RU,ru;q=0.9,en-US;q=0.8,en;q=0.7'}
url = "https://cdn.programiz.com/sites/tutorial2program/files/hello-world.jpg"
try:
content = requests.get(url, headers=headers).content
self.data.emit(content)
except requests.exceptions.ConnectionError as error:
print(error)
class MainWindow(QMainWindow):
# Переопределяем конструктор класса
def __init__(self):
# Обязательно нужно вызвать метод супер класса
super().__init__()
self.pixmap = QPixmap()
self.setMinimumSize(QSize(800, 300)) # Устанавливаем размеры
self.setWindowTitle("Загрузка изображения из интернета")# Устанавливаем заголовок окна
central_widget = QWidget(self) # Создаём центральный виджет
self.setCentralWidget(central_widget) # Устанавливаем центральный виджет
grid_layout = QGridLayout() # Создаём QGridLayout
central_widget.setLayout(grid_layout) # Устанавливаем данное размещение в центральный виджет
self.table = QTableWidget(self) # Создаём таблицу
self.table.setColumnCount(1)
self.table.setRowCount(1) # и одну строку в таблице
# Устанавливаем заголовки таблицы
self.table.setHorizontalHeaderLabels(["Изображение"])
# Устанавливаем всплывающие подсказки на заголовки
self.table.horizontalHeaderItem(0)
self.table.horizontalHeaderItem(0).setToolTip("Шутка")
# Устанавливаем выравнивание на заголовки
self.table.horizontalHeaderItem(0).setTextAlignment(Qt.AlignLeft)
# делаем ресайз колонок по содержимому
self.table.resizeColumnsToContents()
grid_layout.addWidget(self.table, 0, 0) # Добавляем таблицу в сетку
self.upload_image = UploadImage()
self.upload_image.start()
self.upload_image.data.connect(self.show_image)
def show_image(self, image_bytes):
self.bytes_io = BytesIO(image_bytes)
self.pixmap.loadFromData(self.bytes_io.getvalue())
image = QTableWidgetItem()
image.setData(Qt.DecorationRole, self.pixmap)
image.setFlags(image.flags() ^ Qt.ItemIsEditable)
self.table.setItem(0, 0, image)
self.table.resizeColumnsToContents()
if __name__ == "__main__":
import sys
app = QApplication(sys.argv)
mw = MainWindow()
mw.show()
sys.exit(app.exec())
import sys
from PyQt5.QtWidgets import *
from PyQt5.QtCore import Qt
class Example(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.setGeometry(300, 300, 300, 200)
self.setWindowTitle('Example')
self.setWindowFlags(Qt.WindowMaximizeButtonHint)
if __name__ == '__main__':
app = QApplication(sys.argv)
example = Example()
example.show()
sys.exit(app.exec_())
import sys
from PyQt5.QtWidgets import *
from PyQt5.QtCore import Qt
class PopupMenu(QWidget):
def __init__(self):
super().__init__()
self.setWindowTitle('Пример всплывающего меню')
self.resize(300, 300)
self.label = QLabel(self)
self.label.setText("МЕНЮ")
self.popup_menu = QLabel(self)
self.popup_menu.resize(180, 100)
self.popup_menu.setText("Hello PyQt5!")
self.popup_menu.setStyleSheet("border: 2px solid grey; font: 75 italic 16pt Verdana;\
text-align: center; border-radius: 10px;\
background-color: lightblue; width: 10px;")
self.popup_menu.hide()
hbox = QHBoxLayout()
hbox.setAlignment(Qt.AlignCenter)
hbox.addStretch(2)
hbox.addWidget(self.label)
hbox.addWidget(self.popup_menu)
self.label.installEventFilter(self)
def eventFilter(self, obj, event):
# Если мышь над виджетом
if event.type() == 10:
self.popup_menu.show()
# Если мышь покинула область виджета
elif event.type() == 11:
pass
return False
if __name__ == '__main__':
app = QApplication(sys.argv)
window = PopupMenu()
window.show()
sys.exit(app.exec_())
import os
import sys
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
def log_uncaught_exceptions(ex_cls, ex, tb):
import traceback
text = '{}: {}:\n\n'.format(ex_cls.__name__, ex)
text += ''.join(traceback.format_tb(tb))
QMessageBox.critical(None, 'Ошибка!', text)
sys.excepthook = log_uncaught_exceptions
class EnterName(QWidget):
text_value = pyqtSignal(str)
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.setGeometry(300, 300, 300, 50)
self.setWindowTitle('Введите имя')
self.button = QPushButton('Сохранить', self)
self.button.clicked.connect(self.bEvent)
self.button.move(120, 30)
self.lEdid = QLineEdit(self)
self.lEdid.setGeometry(0, 0, 300, 30)
@pyqtSlot()
def bEvent(self):
self.text_value.emit(self.lEdid.text())
self.hide()
class Example(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.setGeometry(300, 300, 420, 280)
self.setWindowTitle('Exsample')
self.button = QPushButton('Имя', self)
self.button.move(180, 260)
self.button.clicked.connect(self.bEvent)
self.tb = QTextBrowser(self)
self.tb.setGeometry(0, 0, 420, 260)
self.eName = EnterName()
self.eName.text_value.connect(self.signalHandler)
def bEvent(self):
self.eName.show()
def signalHandler(self, text):
self.tb.append(text)
if __name__ == '__main__':
app = QApplication(sys.argv)
example = Example()
example.show()
sys.exit(app.exec_())
import sys
from PyQt5.QtWidgets import *
import rsa
class Example(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("Пример")
self.textBrowser = QTextBrowser(self)
self.textBrowser.move(0, 50)
self.textEdit = QTextEdit(self)
self.textEdit.append("Hello world!")
text = self.textEdit.toPlainText()
(pubkey, privkey) = rsa.newkeys(700)
# шифруем
crypto = rsa.encrypt(text.encode(), pubkey)
print(crypto)
# записываем в файл
file = open("my_file.bin", "wb").write(crypto)
# открываем файл в режиме чтения байтов
file = open("my_file.bin", "rb").read()
#расшифровываем
self.text = rsa.decrypt(file, privkey)
self.textBrowser.append(self.text.decode())
print(text)
if __name__ == '__main__':
app = QApplication(sys.argv)
form = Example()
form.show()
app.exec()
import sys
from PyQt5.QtWidgets import (QWidget, QHBoxLayout, QLabel, QApplication)
from PyQt5.QtGui import QPixmap
class Example(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
hbox = QHBoxLayout(self)
pixmap = QPixmap("ёлка.png")
lbl = QLabel(self)
lbl.setPixmap(pixmap)
hbox.addWidget(lbl)
self.setLayout(hbox)
self.move(100, 200)
self.setWindowTitle('Red Rock')
self.show()
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
import sys
from PyQt5.QtWidgets import (QWidget, QLabel,
QLineEdit, QApplication)
class Example(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.lbl = QLabel(self)
qle = QLineEdit(self)
qle.move(60, 100)
self.lbl.move(60, 40)
qle.textChanged[str].connect(self.onChanged)
self.setGeometry(300, 300, 280, 170)
self.setWindowTitle('QLineEdit')
self.show()
def onChanged(self, text):
self.lbl.setText(text)
self.lbl.adjustSize()
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())