I want to embed Kernel Density Estimation plot on PyQt5 GUI using Geoplot library. I found out how to embed simple matplot through canvas and followed same steps for KDE plot but all in vain. GUI opens but doesn't embed KDE. When I close qt GUI, the result is executed at the end of code.
Here is my implemented code:
#Imports
import csv
import os
import sys
from os.path import dirname, realpath,join
from PyQt5.QtGui import QIcon
from PyQt5.QtWidgets import QApplication, QMainWindow,QVBoxLayout,QAction,QFileDialog, QWidget
from PyQt5.uic import loadUiType
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar
from matplotlib.figure import Figure
from PyQt5 import QtCore, QtGui, QtWidgets
import subprocess
import pandas as pd
from matplotlib import pyplot as plt
from matplotlib import rcParams
import seaborn as sns
%matplotlib inline
import numpy as np
from pandas.plotting import register_matplotlib_converters
from datetime import datetime
from statsmodels.tsa.seasonal import STL
import geopandas as gpd
import geoplot as gplt
import geoplot.crs as gcrs
class Ui_Healthcare(object):
def setupUi(self, Healthcare):
Healthcare.setObjectName("Healthcare")
Healthcare.resize(779, 567)
self.centralwidget = QtWidgets.QWidget(Healthcare)
self.centralwidget.setObjectName("centralwidget")
self.All_Gen = QtWidgets.QRadioButton(self.centralwidget)
self.All_Gen.setGeometry(QtCore.QRect(30, 60, 95, 20))
self.All_Gen.setObjectName("All_Gen")
self.Male = QtWidgets.QRadioButton(self.centralwidget)
self.Male.setGeometry(QtCore.QRect(30, 90, 95, 20))
self.Male.setObjectName("Male")
self.Female = QtWidgets.QRadioButton(self.centralwidget)
self.Female.setGeometry(QtCore.QRect(30, 120, 95, 20))
self.Female.setObjectName("Female")
self.Undefined = QtWidgets.QRadioButton(self.centralwidget)
self.Undefined.setGeometry(QtCore.QRect(30, 150, 95, 20))
self.Undefined.setObjectName("Undefined")
self.groupBox = QtWidgets.QGroupBox(self.centralwidget)
self.groupBox.setGeometry(QtCore.QRect(20, 20, 161, 301))
self.groupBox.setStyleSheet("border-color: rgb(0, 0, 0);")
self.groupBox.setObjectName("groupBox")
self.groupBox_2 = QtWidgets.QGroupBox(self.groupBox)
self.groupBox_2.setGeometry(QtCore.QRect(0, 180, 161, 111))
self.groupBox_2.setObjectName("groupBox_2")
self.Age_1 = QtWidgets.QSpinBox(self.groupBox_2)
self.Age_1.setGeometry(QtCore.QRect(30, 30, 42, 22))
self.Age_1.setObjectName("Age_1")
self.Age_2 = QtWidgets.QSpinBox(self.groupBox_2)
self.Age_2.setGeometry(QtCore.QRect(100, 30, 42, 22))
self.Age_2.setObjectName("Age_2")
self.label = QtWidgets.QLabel(self.groupBox_2)
self.label.setGeometry(QtCore.QRect(80, 30, 21, 16))
self.label.setObjectName("label")
self.Age_3 = QtWidgets.QSpinBox(self.groupBox_2)
self.Age_3.setGeometry(QtCore.QRect(30, 70, 42, 22))
self.Age_3.setObjectName("Age_3")
self.label_3 = QtWidgets.QLabel(self.groupBox_2)
self.label_3.setGeometry(QtCore.QRect(80, 70, 21, 16))
self.label_3.setObjectName("label_3")
self.Age_4 = QtWidgets.QSpinBox(self.groupBox_2)
self.Age_4.setGeometry(QtCore.QRect(100, 70, 42, 22))
self.Age_4.setObjectName("Age_4")
self.Age_Lim1 = QtWidgets.QCheckBox(self.groupBox_2)
self.Age_Lim1.setGeometry(QtCore.QRect(10, 30, 16, 20))
self.Age_Lim1.setText("")
self.Age_Lim1.setObjectName("Age_Lim1")
self.Age_Lim2 = QtWidgets.QCheckBox(self.groupBox_2)
self.Age_Lim2.setGeometry(QtCore.QRect(10, 70, 16, 20))
self.Age_Lim2.setText("")
self.Age_Lim2.setObjectName("Age_Lim2")
self.TimeSeries = QtWidgets.QCheckBox(self.centralwidget, clicked = lambda: self.timeseries())
self.TimeSeries.setGeometry(QtCore.QRect(30, 360, 111, 20))
self.TimeSeries.setObjectName("TimeSeries")
self.KDE = QtWidgets.QCheckBox(self.centralwidget, clicked = lambda: self.KDEplot())
self.KDE.setGeometry(QtCore.QRect(30, 390, 121, 20))
self.KDE.setObjectName("KDE")
self.Histograms = QtWidgets.QCheckBox(self.centralwidget)
self.Histograms.setGeometry(QtCore.QRect(30, 420, 121, 20))
self.Histograms.setObjectName("Histograms")
self.Anomalies = QtWidgets.QCheckBox(self.centralwidget)
self.Anomalies.setGeometry(QtCore.QRect(30, 600, 121, 20))
self.Anomalies.setObjectName("Anomalies")
self.AllPatients = QtWidgets.QCheckBox(self.centralwidget)
self.AllPatients.setGeometry(QtCore.QRect(30, 330, 121, 20))
self.AllPatients.setObjectName("AllPatients")
self.line = QtWidgets.QFrame(self.centralwidget)
self.line.setGeometry(QtCore.QRect(180, -10, 20, 731))
self.line.setFrameShape(QtWidgets.QFrame.VLine)
self.line.setFrameShadow(QtWidgets.QFrame.Sunken)
self.line.setObjectName("line")
self.KDE_plot = QtWidgets.QFrame(self.centralwidget)
self.KDE_plot.setGeometry(QtCore.QRect(200, 40, 381, 411))
self.KDE_plot.setFrameShape(QtWidgets.QFrame.StyledPanel)
self.KDE_plot.setFrameShadow(QtWidgets.QFrame.Raised)
self.KDE_plot.setObjectName("KDE_plot")
#create a horizontal layout
self.horizontalLayout_4 = QtWidgets.QHBoxLayout(self.KDE_plot)
self.horizontalLayout_4.setObjectName("horizontalLayout_4")
#Canvas here
self.figure = plt.figure()
self.canvas = FigureCanvas(self.figure)
self.toolbar = NavigationToolbar(self.canvas)
#end of canvas
#Add canvas
self.horizontalLayout_4.addWidget(self.canvas)
self.horizontalLayout_4.addWidget(self.toolbar)
#end of horizontal layout
self.Smallframe1 = QtWidgets.QFrame(self.centralwidget)
self.Smallframe1.setGeometry(QtCore.QRect(600, 40, 161, 111))
self.Smallframe1.setFrameShape(QtWidgets.QFrame.StyledPanel)
self.Smallframe1.setFrameShadow(QtWidgets.QFrame.Raised)
self.Smallframe1.setObjectName("Smallframe1")
self.smallframe2 = QtWidgets.QFrame(self.centralwidget)
self.smallframe2.setGeometry(QtCore.QRect(600, 170, 151, 111))
self.smallframe2.setFrameShape(QtWidgets.QFrame.StyledPanel)
self.smallframe2.setFrameShadow(QtWidgets.QFrame.Raised)
self.smallframe2.setObjectName("smallframe2")
self.smallframe3 = QtWidgets.QFrame(self.centralwidget)
self.smallframe3.setGeometry(QtCore.QRect(600, 310, 151, 121))
self.smallframe3.setFrameShape(QtWidgets.QFrame.StyledPanel)
self.smallframe3.setFrameShadow(QtWidgets.QFrame.Raised)
self.smallframe3.setObjectName("smallframe3")
Healthcare.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(Healthcare)
self.menubar.setGeometry(QtCore.QRect(0, 0, 779, 21))
self.menubar.setObjectName("menubar")
self.menuFile = QtWidgets.QMenu(self.menubar)
self.menuFile.setObjectName("menuFile")
self.menuEdit = QtWidgets.QMenu(self.menubar)
self.menuEdit.setObjectName("menuEdit")
self.menuHelp = QtWidgets.QMenu(self.menubar)
self.menuHelp.setObjectName("menuHelp")
Healthcare.setMenuBar(self.menubar)
self.statusbar = QtWidgets.QStatusBar(Healthcare)
self.statusbar.setObjectName("statusbar")
Healthcare.setStatusBar(self.statusbar)
self.actionImport = QtWidgets.QAction(Healthcare)
self.actionImport.setObjectName("actionImport")
self.actionOpen = QtWidgets.QAction(Healthcare)
self.actionOpen.setObjectName("actionOpen")
self.actionSave = QtWidgets.QAction(Healthcare)
self.actionSave.setObjectName("actionSave")
self.menuFile.addAction(self.actionImport)
self.menuFile.addAction(self.actionOpen)
self.menuFile.addAction(self.actionSave)
self.menubar.addAction(self.menuFile.menuAction())
self.menubar.addAction(self.menuEdit.menuAction())
self.menubar.addAction(self.menuHelp.menuAction())
self.retranslateUi(Healthcare)
QtCore.QMetaObject.connectSlotsByName(Healthcare)
path = self.actionImport.triggered.connect(self.browsefiles)
def retranslateUi(self, Healthcare):
_translate = QtCore.QCoreApplication.translate
Healthcare.setWindowTitle(_translate("Healthcare", "MainWindow"))
self.All_Gen.setText(_translate("Healthcare", "All"))
self.Male.setText(_translate("Healthcare", "Male"))
self.Female.setText(_translate("Healthcare", "Female"))
self.Undefined.setText(_translate("Healthcare", "Undefined "))
self.groupBox.setTitle(_translate("Healthcare", "Demographics"))
self.groupBox_2.setTitle(_translate("Healthcare", "Age"))
self.label.setText(_translate("Healthcare", "To"))
self.label_3.setText(_translate("Healthcare", "To"))
self.TimeSeries.setText(_translate("Healthcare", "Time Series"))
self.KDE.setText(_translate("Healthcare", "Kernel Density"))
self.Histograms.setText(_translate("Healthcare", "Histograms"))
self.Anomalies.setText(_translate("Healthcare", "Anomalies"))
self.AllPatients.setText(_translate("Healthcare", "All patients"))
self.menuFile.setTitle(_translate("Healthcare", "File"))
self.menuEdit.setTitle(_translate("Healthcare", "Edit"))
self.menuHelp.setTitle(_translate("Healthcare", "Help"))
self.actionImport.setText(_translate("Healthcare", "Import"))
self.actionImport.setStatusTip(_translate("Healthcare", "Import Dataset"))
self.actionOpen.setText(_translate("Healthcare", "Open"))
self.actionSave.setText(_translate("Healthcare", "Save"))
def browsefiles(self):
path=QFileDialog.getOpenFileName(None, 'Open file', os.getenv('HOME'), "CSV(*.csv)")
print(path[0])
self.df = pd.read_csv(path[0], index_col = "Date")
def KDEplot(self):
self.figure.clear()
lahore = gpd.read_file(r"C:\Users\drfak\Toolkit\Lahore towns uc and vill\LH_TOWNS-2006_GEO_AREAS.shp")
dataset = pd.read_csv("ABCD.csv")
dataset = gpd.GeoDataFrame(dataset, geometry=gpd.points_from_xy(dataset.Longitude, dataset.Latitude))
gplt.kdeplot(dataset, cmap='Reds', fill = True, clip=lahore)
gplt.polyplot(lahore , ax=ax, zorder =1)
self.canvas.draw()
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
Healthcare = QtWidgets.QMainWindow()
ui = Ui_Healthcare()
ui.setupUi(Healthcare)
Healthcare.show()
sys.exit(app.exec_())
Related
I am trying to add a plot into qt window, but i can't fit that into the window it is overflowing how to properly place the plot into qt window?
i created a frame with width 650 and height 600 and i want to add plot into this frame
self.XYFrame = QtWidgets.QFrame(self.top)
self.XYFrame.setMinimumSize(QtCore.QSize(650, 600))
self.XYFrame.setMaximumSize(QtCore.QSize(650, 600))
self.XYFrame.setFrameShape(QtWidgets.QFrame.StyledPanel)
self.XYFrame.setFrameShadow(QtWidgets.QFrame.Raised)
self.XYFrame.setObjectName("XYFrame")
self.horizontalLayout_9 = QtWidgets.QHBoxLayout(self.XYFrame)
self.horizontalLayout_9.setObjectName("horizontalLayout_9")
xy_plot = self.plot.plotXY()
self.plotWidget = FigureCanvas(xy_plot)
self.horizontalLayout_9.addWidget(self.plotWidget)
self.horizontalLayout_7.addWidget(self.XYFrame)
Here is my plotXY()
def plotXY(self):
height, parameter = self.connection.XYPlotData()
fig, ax = plt.subplots()
ax.set(xlabel = "Relative humidity", ylabel = "Height")
ax.plot(height, parameter)
return fig
this how the plot looks now i wanted fit the plot completely into window with weigh background without overflowing
i tried fig.tight_layout() and fig.subplots_adjust(0.2, 0.2, 0.8, 0.8) in plotXY() but it's not working
code for testing
main.py
import sys
from PyQt5.QtWidgets import QApplication,QMainWindow
from ui import *
# from mainWindowUI import *
class MainWindow(QMainWindow):
def __init__(self, parent=None):
QMainWindow.__init__(self)
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
if __name__ == '__main__':
app = QApplication(sys.argv)
mainWindow = MainWindow()
mainWindow.setWindowState(QtCore.Qt.WindowMaximized)
mainWindow.show()
sys.exit(app.exec_())
ui.py
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file '.\ui\mainWInLay.ui'
#
# Created by: PyQt5 UI code generator 5.15.4
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again. Do not edit this file unless you know what you are doing.
from PyQt5 import QtCore, QtGui, QtWidgets
# from PyQt5.QtWebEngineWidgets import QWebEngineView
from matplotlib.backends.backend_qt5agg import FigureCanvas
import matplotlib.pyplot as plt
x = [100, 125, 150, 175, 200, 225, 250, 300, 350, 400, 450, 500, 550, 600, 650,700, 750, 775, 800, 825, 850, 875, 900, 925,950,975,1000]
y = [104.355,89.6661,86.6984,78.7212,104.783,103.04,53.765,21.0933,21.8741,24.0535,28.5814,46.6883,61.0047,79.1699,87.5734,89.2936,88.4784,86.8854,84.4816,82.6208,82.166,82.0942,83.798,82.3396,77.1371,82.0763,76.2785]
def plotXY():
height, parameter = x, y
fig, ax = plt.subplots()
ax.set(xlabel = "Relative humidity", ylabel = "Height")
ax.plot(height, parameter)
return fig
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(1389, 600)
MainWindow.setStyleSheet("")
# self.plot = Plot()
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setStyleSheet("background-color: rgb(43, 54, 72);")
self.centralwidget.setObjectName("centralwidget")
self.horizontalLayout = QtWidgets.QHBoxLayout(self.centralwidget)
self.horizontalLayout.setObjectName("horizontalLayout")
self.mainFrame = QtWidgets.QFrame(self.centralwidget)
self.mainFrame.setFrameShape(QtWidgets.QFrame.StyledPanel)
self.mainFrame.setFrameShadow(QtWidgets.QFrame.Raised)
self.mainFrame.setObjectName("mainFrame")
self.verticalLayout = QtWidgets.QVBoxLayout(self.mainFrame)
self.verticalLayout.setContentsMargins(0, 0, 0, 0)
self.verticalLayout.setObjectName("verticalLayout")
self.top = QtWidgets.QFrame(self.mainFrame)
self.top.setFrameShape(QtWidgets.QFrame.StyledPanel)
self.top.setFrameShadow(QtWidgets.QFrame.Raised)
self.top.setObjectName("top")
self.horizontalLayout_7 = QtWidgets.QHBoxLayout(self.top)
self.horizontalLayout_7.setContentsMargins(0, 0, 0, 0)
self.horizontalLayout_7.setObjectName("horizontalLayout_7")
self.contourFrame = QtWidgets.QFrame(self.top)
self.contourFrame.setMinimumSize(QtCore.QSize(650, 600))
self.contourFrame.setMaximumSize(QtCore.QSize(650, 600))
self.contourFrame.setFrameShape(QtWidgets.QFrame.StyledPanel)
self.contourFrame.setFrameShadow(QtWidgets.QFrame.Raised)
self.contourFrame.setObjectName("contourFrame")
self.horizontalLayout_8 = QtWidgets.QHBoxLayout(self.contourFrame)
self.horizontalLayout_8.setContentsMargins(0, 0, 0, 0)
self.horizontalLayout_8.setSpacing(0)
self.horizontalLayout_8.setObjectName("horizontalLayout_8")
# self.url = QtCore.QUrl.fromLocalFile(r"data.html")
# self.webview = QWebEngineView(self.contourFrame)
# self.webview.load(self.url)
# # self.widget = QtWidgets.QWidget(self.contourFrame)
# # self.widget.setStyleSheet("")
# # self.widget.setObjectName("widget")
# self.horizontalLayout_8.addWidget(self.webview)
#----------------------------------------------------------------------------------------
# HERE IS THE FRAME THAT I WANT TO INSRET MY PLOT
self.horizontalLayout_7.addWidget(self.contourFrame)
self.XYFrame = QtWidgets.QFrame(self.top)
self.XYFrame.setMinimumSize(QtCore.QSize(650, 600))
self.XYFrame.setMaximumSize(QtCore.QSize(650, 600))
self.XYFrame.setFrameShape(QtWidgets.QFrame.StyledPanel)
self.XYFrame.setFrameShadow(QtWidgets.QFrame.Raised)
self.XYFrame.setObjectName("XYFrame")
self.horizontalLayout_9 = QtWidgets.QHBoxLayout(self.XYFrame)
self.horizontalLayout_9.setObjectName("horizontalLayout_9")
xy_plot = plotXY()
self.plotWidget = FigureCanvas(xy_plot)
self.horizontalLayout_9.addWidget(self.plotWidget)
#----------------------------------------------------------------------------------------
self.horizontalLayout_7.addWidget(self.XYFrame)
self.verticalLayout.addWidget(self.top)
self.bottom = QtWidgets.QFrame(self.mainFrame)
self.bottom.setMinimumSize(QtCore.QSize(0, 250))
self.bottom.setMaximumSize(QtCore.QSize(16777215, 250))
self.bottom.setFrameShape(QtWidgets.QFrame.StyledPanel)
self.bottom.setFrameShadow(QtWidgets.QFrame.Raised)
self.bottom.setObjectName("bottom")
self.horizontalLayout_2 = QtWidgets.QHBoxLayout(self.bottom)
self.horizontalLayout_2.setContentsMargins(0, 0, 0, 0)
self.horizontalLayout_2.setSpacing(10)
self.horizontalLayout_2.setObjectName("horizontalLayout_2")
self.selectionFrame = QtWidgets.QFrame(self.bottom)
self.selectionFrame.setMinimumSize(QtCore.QSize(500, 250))
self.selectionFrame.setMaximumSize(QtCore.QSize(500, 250))
self.selectionFrame.setStyleSheet("background-color: rgb(0, 0, 0);")
self.selectionFrame.setFrameShape(QtWidgets.QFrame.StyledPanel)
self.selectionFrame.setFrameShadow(QtWidgets.QFrame.Raised)
self.selectionFrame.setObjectName("selectionFrame")
self.verticalLayout_2 = QtWidgets.QVBoxLayout(self.selectionFrame)
self.verticalLayout_2.setObjectName("verticalLayout_2")
self.dayMonFrame = QtWidgets.QFrame(self.selectionFrame)
self.dayMonFrame.setFrameShape(QtWidgets.QFrame.StyledPanel)
self.dayMonFrame.setFrameShadow(QtWidgets.QFrame.Raised)
self.dayMonFrame.setObjectName("dayMonFrame")
self.horizontalLayout_3 = QtWidgets.QHBoxLayout(self.dayMonFrame)
self.horizontalLayout_3.setObjectName("horizontalLayout_3")
self.dayLabel = QtWidgets.QLabel(self.dayMonFrame)
self.dayLabel.setMinimumSize(QtCore.QSize(100, 25))
self.dayLabel.setMaximumSize(QtCore.QSize(100, 25))
self.dayLabel.setStyleSheet("color: rgb(86, 101, 127);\n"
"font-size:18px;")
self.dayLabel.setObjectName("dayLabel")
self.horizontalLayout_3.addWidget(self.dayLabel)
self.daySpinBox = QtWidgets.QSpinBox(self.dayMonFrame)
self.daySpinBox.setMinimumSize(QtCore.QSize(100, 25))
self.daySpinBox.setMaximumSize(QtCore.QSize(100, 25))
self.daySpinBox.setStyleSheet("background-color: rgb(255, 255, 255);")
self.daySpinBox.setObjectName("daySpinBox")
self.horizontalLayout_3.addWidget(self.daySpinBox)
self.monLabel = QtWidgets.QLabel(self.dayMonFrame)
self.monLabel.setMinimumSize(QtCore.QSize(100, 25))
self.monLabel.setMaximumSize(QtCore.QSize(100, 25))
self.monLabel.setStyleSheet("color: rgb(86, 101, 127);\n"
"font-size:18px;")
self.monLabel.setObjectName("monLabel")
self.horizontalLayout_3.addWidget(self.monLabel)
self.monSpinBox = QtWidgets.QSpinBox(self.dayMonFrame)
self.monSpinBox.setMinimumSize(QtCore.QSize(100, 25))
self.monSpinBox.setMaximumSize(QtCore.QSize(100, 25))
self.monSpinBox.setStyleSheet("background-color: rgb(255, 255, 255);")
self.monSpinBox.setObjectName("monSpinBox")
self.horizontalLayout_3.addWidget(self.monSpinBox)
self.verticalLayout_2.addWidget(self.dayMonFrame)
self.paramprsFrame = QtWidgets.QFrame(self.selectionFrame)
self.paramprsFrame.setFrameShape(QtWidgets.QFrame.StyledPanel)
self.paramprsFrame.setFrameShadow(QtWidgets.QFrame.Raised)
self.paramprsFrame.setObjectName("paramprsFrame")
self.horizontalLayout_4 = QtWidgets.QHBoxLayout(self.paramprsFrame)
self.horizontalLayout_4.setObjectName("horizontalLayout_4")
self.label = QtWidgets.QLabel(self.paramprsFrame)
self.label.setMinimumSize(QtCore.QSize(100, 25))
self.label.setMaximumSize(QtCore.QSize(100, 25))
self.label.setStyleSheet("color: rgb(86, 101, 127);\n"
"font-size:18px;")
self.label.setObjectName("label")
self.horizontalLayout_4.addWidget(self.label)
self.comboBox = QtWidgets.QComboBox(self.paramprsFrame)
self.comboBox.setMinimumSize(QtCore.QSize(100, 25))
self.comboBox.setMaximumSize(QtCore.QSize(100, 25))
self.comboBox.setStyleSheet("background-color: rgb(255, 255, 255);")
self.comboBox.setObjectName("comboBox")
self.horizontalLayout_4.addWidget(self.comboBox)
self.label_2 = QtWidgets.QLabel(self.paramprsFrame)
self.label_2.setMinimumSize(QtCore.QSize(100, 25))
self.label_2.setMaximumSize(QtCore.QSize(100, 25))
self.label_2.setStyleSheet("color: rgb(86, 101, 127);\n"
"font-size:18px;")
self.label_2.setObjectName("label_2")
self.horizontalLayout_4.addWidget(self.label_2)
self.comboBox_2 = QtWidgets.QComboBox(self.paramprsFrame)
self.comboBox_2.setMinimumSize(QtCore.QSize(100, 25))
self.comboBox_2.setMaximumSize(QtCore.QSize(100, 25))
self.comboBox_2.setStyleSheet("background-color: rgb(255, 255, 255);")
self.comboBox_2.setObjectName("comboBox_2")
self.horizontalLayout_4.addWidget(self.comboBox_2)
self.verticalLayout_2.addWidget(self.paramprsFrame)
self.latLonFrame = QtWidgets.QFrame(self.selectionFrame)
self.latLonFrame.setFrameShape(QtWidgets.QFrame.StyledPanel)
self.latLonFrame.setFrameShadow(QtWidgets.QFrame.Raised)
self.latLonFrame.setObjectName("latLonFrame")
self.horizontalLayout_5 = QtWidgets.QHBoxLayout(self.latLonFrame)
self.horizontalLayout_5.setObjectName("horizontalLayout_5")
self.label_3 = QtWidgets.QLabel(self.latLonFrame)
self.label_3.setMinimumSize(QtCore.QSize(100, 25))
self.label_3.setMaximumSize(QtCore.QSize(100, 25))
self.label_3.setStyleSheet("color: rgb(86, 101, 127);\n"
"font-size:18px;")
self.label_3.setObjectName("label_3")
self.horizontalLayout_5.addWidget(self.label_3)
self.comboBox_3 = QtWidgets.QComboBox(self.latLonFrame)
self.comboBox_3.setMinimumSize(QtCore.QSize(100, 25))
self.comboBox_3.setMaximumSize(QtCore.QSize(100, 25))
self.comboBox_3.setStyleSheet("background-color: rgb(255, 255, 255);")
self.comboBox_3.setObjectName("comboBox_3")
self.horizontalLayout_5.addWidget(self.comboBox_3)
self.label_4 = QtWidgets.QLabel(self.latLonFrame)
self.label_4.setMinimumSize(QtCore.QSize(100, 25))
self.label_4.setMaximumSize(QtCore.QSize(100, 25))
self.label_4.setStyleSheet("color: rgb(86, 101, 127);\n"
"font-size:18px;")
self.label_4.setObjectName("label_4")
self.horizontalLayout_5.addWidget(self.label_4)
self.comboBox_4 = QtWidgets.QComboBox(self.latLonFrame)
self.comboBox_4.setMinimumSize(QtCore.QSize(100, 25))
self.comboBox_4.setMaximumSize(QtCore.QSize(100, 25))
self.comboBox_4.setStyleSheet("background-color: rgb(255, 255, 255);")
self.comboBox_4.setObjectName("comboBox_4")
self.horizontalLayout_5.addWidget(self.comboBox_4)
self.verticalLayout_2.addWidget(self.latLonFrame)
self.btnFrame = QtWidgets.QFrame(self.selectionFrame)
self.btnFrame.setFrameShape(QtWidgets.QFrame.StyledPanel)
self.btnFrame.setFrameShadow(QtWidgets.QFrame.Raised)
self.btnFrame.setObjectName("btnFrame")
self.pushButton = QtWidgets.QPushButton(self.btnFrame)
self.pushButton.setGeometry(QtCore.QRect(190, 10, 125, 35))
self.pushButton.setMinimumSize(QtCore.QSize(125, 35))
self.pushButton.setMaximumSize(QtCore.QSize(125, 35))
self.pushButton.setStyleSheet("background-color: rgb(255, 255, 255);\n"
"border:1px solid black;\n"
"border-radius:15px;")
self.pushButton.setObjectName("pushButton")
self.verticalLayout_2.addWidget(self.btnFrame)
self.horizontalLayout_2.addWidget(self.selectionFrame)
self.timeFrame = QtWidgets.QFrame(self.bottom)
self.timeFrame.setMinimumSize(QtCore.QSize(825, 250))
self.timeFrame.setMaximumSize(QtCore.QSize(825, 250))
self.timeFrame.setStyleSheet("background-color: rgb(0, 0, 0);")
self.timeFrame.setFrameShape(QtWidgets.QFrame.StyledPanel)
self.timeFrame.setFrameShadow(QtWidgets.QFrame.Raised)
self.timeFrame.setObjectName("timeFrame")
self.horizontalLayout_6 = QtWidgets.QHBoxLayout(self.timeFrame)
self.horizontalLayout_6.setContentsMargins(0, 0, 0, 0)
self.horizontalLayout_6.setSpacing(0)
self.horizontalLayout_6.setObjectName("horizontalLayout_6")
# self.timeWidget = QtWidgets.QWidget(self.timeFrame)
# self.timeWidget.setObjectName("timeWidget")
# self.time_plot = self.plot.plotTime(13, 1)
# self.timePlotWindow = FigureCanvas(self.time_plot)
# self.horizontalLayout_6.addWidget(self.timePlotWindow)
self.horizontalLayout_2.addWidget(self.timeFrame)
self.verticalLayout.addWidget(self.bottom)
self.horizontalLayout.addWidget(self.mainFrame)
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 1389, 21))
self.menubar.setObjectName("menubar")
MainWindow.setMenuBar(self.menubar)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.dayLabel.setText(_translate("MainWindow", "Day"))
self.monLabel.setText(_translate("MainWindow", "Month"))
self.label.setText(_translate("MainWindow", "Parameters"))
self.label_2.setText(_translate("MainWindow", "Pressure"))
self.label_3.setText(_translate("MainWindow", "Latitude"))
self.label_4.setText(_translate("MainWindow", "Longitude"))
self.pushButton.setText(_translate("MainWindow", "PushButton"))
I'm using Qt Designer to build an application in Python, which needs to show a graph in the main application window with buttons and the main program. I'm using PyQtGraph for the plot.
Here is the code:
from PyQt5 import QtCore, QtGui, QtWidgets
import pyqtgraph as pg
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(668, 458)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.labelx = QtWidgets.QLabel(self.centralwidget)
self.labelx.setGeometry(QtCore.QRect(50, 20, 581, 231))
self.labelx.setAutoFillBackground(True)
self.labelx.setFrameShape(QtWidgets.QFrame.Panel)
self.labelx.setFrameShadow(QtWidgets.QFrame.Sunken)
self.labelx.setLineWidth(3)
self.labelx.setMidLineWidth(3)
self.labelx.setText("")
self.labelx.setScaledContents(True)
self.labelx.setObjectName("labelx")
self.label_15 = QtWidgets.QLabel(self.centralwidget)
self.label_15.setGeometry(QtCore.QRect(350, 280, 91, 16))
self.label_15.setObjectName("label_15")
self.lineEdit_13 = QtWidgets.QLineEdit(self.centralwidget)
self.lineEdit_13.setGeometry(QtCore.QRect(230, 280, 113, 20))
self.lineEdit_13.setObjectName("lineEdit_13")
self.lineEdit_14 = QtWidgets.QLineEdit(self.centralwidget)
self.lineEdit_14.setGeometry(QtCore.QRect(230, 310, 113, 20))
self.lineEdit_14.setText("")
self.lineEdit_14.setObjectName("lineEdit_14")
self.label_16 = QtWidgets.QLabel(self.centralwidget)
self.label_16.setGeometry(QtCore.QRect(350, 310, 91, 16))
self.label_16.setObjectName("label_16")
self.pushButton = QtWidgets.QPushButton(self.centralwidget)
self.pushButton.setGeometry(QtCore.QRect(10, 390, 111, 23))
self.pushButton.setObjectName("pushButton")
self.pushButton_2 = QtWidgets.QPushButton(self.centralwidget)
self.pushButton_2.setGeometry(QtCore.QRect(120, 390, 111, 23))
self.pushButton_2.setObjectName("pushButton_2")
self.lineEdit_15 = QtWidgets.QLineEdit(self.centralwidget)
self.lineEdit_15.setGeometry(QtCore.QRect(440, 280, 113, 20))
self.lineEdit_15.setText("")
self.lineEdit_15.setObjectName("lineEdit_15")
self.label_17 = QtWidgets.QLabel(self.centralwidget)
self.label_17.setGeometry(QtCore.QRect(560, 280, 91, 16))
self.label_17.setObjectName("label_17")
self.pushButton_3 = QtWidgets.QPushButton(self.centralwidget)
self.pushButton_3.setGeometry(QtCore.QRect(550, 390, 111, 23))
self.pushButton_3.setObjectName("pushButton_3")
self.pushButton_4 = QtWidgets.QPushButton(self.centralwidget)
self.pushButton_4.setGeometry(QtCore.QRect(230, 340, 111, 23))
self.pushButton_4.setObjectName("pushButton_4")
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 668, 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)
self.pushButton_2.clicked.connect(self.lineEdit_13.clear)
self.pushButton_2.clicked.connect(self.lineEdit_14.clear)
self.pushButton_2.clicked.connect(self.lineEdit_15.clear)
self.pushButton_4.clicked.connect(self.plotwid)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.label_15.setText(_translate("MainWindow", "Total Expenses"))
self.label_16.setText(_translate("MainWindow", "Total Income"))
self.pushButton.setText(_translate("MainWindow", "Add Expenses"))
self.pushButton_2.setText(_translate("MainWindow", "Cleasr All"))
self.label_17.setText(_translate("MainWindow", "Total Savings"))
self.pushButton_3.setText(_translate("MainWindow", "Exit"))
self.pushButton_4.setText(_translate("MainWindow", "Make Graph"))
def plotwid(self):
# define the data
title = "Savings Calculator"
t = int(8)
# y values to plot by line 1
y = [1, 5, 6, 8, 6, 11, 14, 13, 18, 30]
# y values to plot by line 2
y2 = [1, 1, 5, 8, 9, 11, 16, 17, 14, 30]
x = range(0, 10)
# create plot window object
plt = pg.plot()
# showing x and y grids
plt.showGrid(x=True, y=True)
# adding legend
plt.addLegend()
# set properties of the label for y axis
plt.setLabel('left', 'Amount of savings and income', units='y')
# set properties of the label for x axis
plt.setLabel('bottom', 'Months to save', units='s')
# setting horizontal range
plt.setXRange(0, 12)
# setting vertical range
plt.setYRange(0, 1000)
# setting window title
plt.setWindowTitle(title)
# ploting line in green color
line1 = plt.plot(x, y, pen='g', symbol='x', symbolPen='g',
symbolBrush=0.2, name='green')
# ploting line2 with blue color
line2 = plt.plot(x, y2, pen='b', symbol='o', symbolPen='b',
symbolBrush=0.2, name='blue')
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_())
Problem
It always opens in its own window. How can I set it to open in a window within my application window?
First of all, do not modify the code generated by QtDesigner (for more information read here and here) so you must regenerate the file: pyuic5 design.ui -o design.py -x`
Considering the above, the solution is to place the PlotWidget inside "labelx" through a layout (another solution can be to promote the widget):
from PyQt5 import QtCore, QtGui, QtWidgets
import pyqtgraph as pg
from design import Ui_MainWindow
class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
def __init__(self, parent=None):
super().__init__(parent)
self.setupUi(self)
self.pushButton_2.clicked.connect(self.lineEdit_13.clear)
self.pushButton_2.clicked.connect(self.lineEdit_14.clear)
self.pushButton_2.clicked.connect(self.lineEdit_15.clear)
self.pushButton_4.clicked.connect(self.plotwid)
lay = QtWidgets.QVBoxLayout(self.labelx)
lay.setContentsMargins(0, 0, 0, 0)
self.plt = pg.plot()
lay.addWidget(self.plt)
def plotwid(self):
title = "Savings Calculator"
t = 8
# y values to plot by line 1
y = [1, 5, 6, 8, 6, 11, 14, 13, 18, 30]
# y values to plot by line 2
y2 = [1, 1, 5, 8, 9, 11, 16, 17, 14, 30]
x = range(0, 10)
self.plt.showGrid(x=True, y=True)
# adding legend
self.plt.addLegend()
# set properties of the label for y axis
self.plt.setLabel("left", "Amount of savings and income", units="y")
# set properties of the label for x axis
self.plt.setLabel("bottom", "Months to save", units="s")
# setting horizontal range
self.plt.setXRange(0, 12)
# setting vertical range
self.plt.setYRange(0, 1000)
# setting window title
self.plt.setWindowTitle(title)
# ploting line in green color
line1 = self.plt.plot(
x, y, pen="g", symbol="x", symbolPen="g", symbolBrush=0.2, name="green"
)
# ploting line2 with blue color
line2 = self.plt.plot(
x, y2, pen="b", symbol="o", symbolPen="b", symbolBrush=0.2, name="blue"
)
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
w = MainWindow()
w.show()
sys.exit(app.exec_())
I am trying to add some check boxes in scroll area.but for me it is not working properly.i am new in python could anyone help?
import PyQt5
from PyQt5 import QtCore, QtGui, QtWidgets
from configparser import ConfigParser
import paramiko
import threading
import os
if hasattr(QtCore.Qt, 'AA_EnableHighDpiScaling'):
PyQt5.QtWidgets.QApplication.setAttribute(QtCore.Qt.AA_EnableHighDpiScaling, True)
if hasattr(QtCore.Qt, 'AA_UseHighDpiPixmaps'):
PyQt5.QtWidgets.QApplication.setAttribute(QtCore.Qt.AA_UseHighDpiPixmaps, True)
class Ui_MainWindow(object):
def __init__(self, parent=None):
self.configur = ConfigParser()
self.configur.read('ServerConfigurationDetails.ini')
self.serverName=self.configur.sections()
print(self.serverName)
self.getComponents = self.configur.options("Component")
self.sLen = len(self.serverName)
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.setEnabled(True)
MainWindow.resize(951, 634)
font = QtGui.QFont()
font.setPointSize(10)
MainWindow.setFont(font)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.label_2 = QtWidgets.QLabel(self.centralwidget)
self.label_2.setGeometry(QtCore.QRect(150, 220, 91, 31))
font = QtGui.QFont()
font.setPointSize(14)
self.label_2.setFont(font)
self.label_2.setObjectName("label_2")
self.comboBox_2 = QtWidgets.QComboBox(self.centralwidget)
self.comboBox_2.setGeometry(QtCore.QRect(250, 220, 231, 31))
self.comboBox_2.setObjectName("comboBox_2")
self.comboBox_2.addItem("")
self.comboBox_2.addItem("")
self.pushButton = QtWidgets.QPushButton(self.centralwidget)
self.pushButton.setGeometry(QtCore.QRect(700, 40, 101, 31))
self.pushButton.setObjectName("pushButton")
self.groupBox = QtWidgets.QGroupBox(self.centralwidget)
self.groupBox.setGeometry(QtCore.QRect(140, 260, 681, 81))
self.groupBox.setObjectName("groupBox")
self.radioButton = QtWidgets.QRadioButton(self.groupBox)
self.radioButton.setGeometry(QtCore.QRect(10, 30, 201, 20))
self.radioButton.setObjectName("radioButton")
self.radioButton_2 = QtWidgets.QRadioButton(self.groupBox)
self.radioButton_2.setGeometry(QtCore.QRect(220, 30, 201, 20))
self.radioButton_2.setObjectName("radioButton_2")
self.checkBox = QtWidgets.QCheckBox(self.groupBox)
self.checkBox.setEnabled(False)
self.checkBox.setGeometry(QtCore.QRect(10, 50, 231, 31))
self.checkBox.setChecked(True)
self.checkBox.setObjectName("checkBox")
self.radioButton_3 = QtWidgets.QRadioButton(self.groupBox)
self.radioButton_3.setGeometry(QtCore.QRect(420, 30, 171, 20))
self.radioButton_3.setObjectName("radioButton_3")
self.lineEdit = QtWidgets.QLineEdit(self.centralwidget)
self.lineEdit.setGeometry(QtCore.QRect(280, 40, 411, 31))
self.lineEdit.setObjectName("lineEdit")
self.label_3 = QtWidgets.QLabel(self.centralwidget)
self.label_3.setGeometry(QtCore.QRect(130, 40, 131, 31))
self.label_3.setObjectName("label_3")
self.label_5 = QtWidgets.QLabel(self.centralwidget)
self.label_5.setGeometry(QtCore.QRect(140, 125, 661, 21))
self.label_5.setText("")
self.label_5.setObjectName("label_5")
self.scrollArea = QtWidgets.QScrollArea(self.centralwidget)
self.scrollArea.setGeometry(QtCore.QRect(130, 110, 681, 101))
self.scrollArea.setAccessibleDescription("")
self.scrollArea.setWidgetResizable(False)
self.scrollArea.setObjectName("scrollArea")
self.scrollAreaWidgetContents = QtWidgets.QWidget()
self.scrollAreaWidgetContents.setGeometry(QtCore.QRect(0, 0, 679, 99))
self.scrollAreaWidgetContents.setObjectName("scrollAreaWidgetContents")
c=10
n=0
x = 10
y = 10
print(self.sLen)
for i in range(self.sLen):
if(n==4):
n=0
x=10
y=y+20
self.checkbox1 = QtWidgets.QCheckBox(self.scrollAreaWidgetContents)
self.checkbox1.setGeometry(QtCore.QRect(x+1, y+1, 161, 20))
self.checkbox1.setText(self.serverName[i])
self.checkbox1.setObjectName(self.serverName[i])
print(x)
print(n)
n=n+1
if(n==4):
x=10
y = y+20
else:
x= x+180
## self.checkBox_2 = QtWidgets.QCheckBox(self.scrollAreaWidgetContents)
## self.checkBox_2.setGeometry(QtCore.QRect(10, 10, 161, 20))
## self.checkBox_2.setObjectName("checkBox_2")
## self.checkBox_3 = QtWidgets.QCheckBox(self.scrollAreaWidgetContents)
## self.checkBox_3.setGeometry(QtCore.QRect(180, 10, 131, 20))
## self.checkBox_3.setObjectName("checkBox_3")
## self.checkBox_4 = QtWidgets.QCheckBox(self.scrollAreaWidgetContents)
## self.checkBox_4.setGeometry(QtCore.QRect(350, 10, 151, 20))
## self.checkBox_4.setObjectName("checkBox_4")
## self.checkBox_5 = QtWidgets.QCheckBox(self.scrollAreaWidgetContents)
## self.checkBox_5.setGeometry(QtCore.QRect(530, 10, 141, 20))
## self.checkBox_5.setObjectName("checkBox_5")
## self.checkBox_6 = QtWidgets.QCheckBox(self.scrollAreaWidgetContents)
## self.checkBox_6.setGeometry(QtCore.QRect(10, 30, 161, 20))
## self.checkBox_6.setObjectName("checkBox_6")
self.scrollArea.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAsNeeded)
self.scrollArea.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
self.scrollArea.setWidget(self.scrollAreaWidgetContents)
self.scrollArea_2 = QtWidgets.QScrollArea(self.centralwidget)
self.scrollArea_2.setGeometry(QtCore.QRect(140, 380, 681, 191))
self.scrollArea_2.setWidgetResizable(True)
self.scrollArea_2.setObjectName("scrollArea_2")
self.scrollAreaWidgetContents_2 = QtWidgets.QWidget()
self.scrollAreaWidgetContents_2.setGeometry(QtCore.QRect(0, 0, 679, 189))
self.scrollAreaWidgetContents_2.setObjectName("scrollAreaWidgetContents_2")
self.scrollArea_2.setWidget(self.scrollAreaWidgetContents_2)
self.line = QtWidgets.QFrame(self.centralwidget)
self.line.setGeometry(QtCore.QRect(70, 340, 811, 20))
self.line.setFrameShape(QtWidgets.QFrame.HLine)
self.line.setFrameShadow(QtWidgets.QFrame.Sunken)
self.line.setObjectName("line")
MainWindow.setCentralWidget(self.centralwidget)
self.statusbar = QtWidgets.QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 951, 26))
self.menubar.setObjectName("menubar")
self.menuhelp = QtWidgets.QMenu(self.menubar)
self.menuhelp.setObjectName("menuhelp")
MainWindow.setMenuBar(self.menubar)
self.actionAbout = QtWidgets.QAction(MainWindow)
self.actionAbout.setObjectName("actionAbout")
self.menuhelp.addAction(self.actionAbout)
self.menubar.addAction(self.menuhelp.menuAction())
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.label_2.setText(_translate("MainWindow", "<html><head/><body><p><span style=\" font-size:10pt;\">Component</span></p></body></html>"))
self.comboBox_2.setItemText(0, _translate("MainWindow", "eComm"))
self.comboBox_2.setItemText(1, _translate("MainWindow", "workproc"))
self.pushButton.setText(_translate("MainWindow", "Search"))
self.groupBox.setTitle(_translate("MainWindow", "Other Details"))
self.radioButton.setText(_translate("MainWindow", "Only Search in Archive"))
self.radioButton_2.setText(_translate("MainWindow", "Also Search in Archive"))
self.checkBox.setText(_translate("MainWindow", "Auto Download"))
self.radioButton_3.setText(_translate("MainWindow", "Only Search in Log"))
self.label_3.setText(_translate("MainWindow", "<html><head/><body><p>Search String<span style=\" color:#ff0000;\">*</span></p></body></html>"))
## self.checkBox_2.setText(_translate("MainWindow", "CheckBox"))
## self.checkBox_3.setText(_translate("MainWindow", "CheckBox"))
## self.checkBox_4.setText(_translate("MainWindow", "CheckBox"))
## self.checkBox_5.setText(_translate("MainWindow", "CheckBox"))
## self.checkBox_6.setText(_translate("MainWindow", "CheckBox"))
self.menuhelp.setTitle(_translate("MainWindow", "Help"))
self.actionAbout.setText(_translate("MainWindow", "About"))
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_())
as you can see the scroll area is not showing properly.i have some 20 servers to show.this server list is coming from ini file and i need to show the check boxes in that scroll area.
you need to use QLayout to arrange you widgets. check out
Qt Designer -> "Widget Box" docker -> "Layouts" section
For the scrollarea part:
create scrollarea scroll_area = QScrollArea()
create view widget you want to put inside scrollarea base_widget = QWidget()
install view layout for view widget base_layout = QVBoxLayout(base_widget)
install view widget into scrollarea scroll_area.setWidget(base_widget)
fill in objects with view layout base_layout.addWidget(QLabel('foo')) base_layout.addWidget(QPushButton('bar')) base_layout.addLayout(my_sub_layout) etc.
I have a problem displaying the output of a function in a qdialog of pyqt.
My code is as follows:
import sys
import os
import glob
import shutil
import json
import datetime
import time
import requests
from multiprocessing import Queue
start_time = time.time()
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QApplication, QMainWindow, QDialog, QPushButton, QLabel, QScrollArea, QProgressBar, QTextEdit
noreports = len(glob.glob('*.txt'))
class Dialogo(QDialog):
def __init__(self):
QDialog.__init__(self)
self.resize(400, 380)
self.nombre = QLabel(self)
self.nombre.setGeometry(QtCore.QRect(30, 20, 171, 17))
self.nombre.setObjectName("nombre")
self.label = QLabel(self)
self.label.setGeometry(QtCore.QRect(30, 50, 121, 17))
self.label.setObjectName("label")
self.pushButton = QPushButton(self)
self.pushButton.setGeometry(QtCore.QRect(260, 310, 86, 28))
self.pushButton.setObjectName("pushButton")
self.scrollArea = QScrollArea(self)
self.scrollArea.setGeometry(QtCore.QRect(30, 120, 341, 171))
self.scrollArea.setWidgetResizable(True)
self.scrollArea.setObjectName("scrollArea")
self.scrollAreaWidgetContents = QtWidgets.QWidget()
self.scrollAreaWidgetContents.setGeometry(QtCore.QRect(0, 0, 337, 167))
self.scrollAreaWidgetContents.setObjectName("scrollAreaWidgetContents")
self.scrollArea.setWidget(self.scrollAreaWidgetContents)
self.progressBar = QProgressBar(self)
self.progressBar.setGeometry(QtCore.QRect(30, 80, 341, 23))
self.progressBar.setProperty("value", 0)
self.progressBar.setObjectName("progressBar")
self.textEdit = QTextEdit(self)
self.scrollArea.setWidget(self.textEdit)
self.retranslateUi(self)
QtCore.QMetaObject.connectSlotsByName(self)
def retranslateUi(self, Dialogo):
global noreports
_translate = QtCore.QCoreApplication.translate
self.setWindowTitle(_translate("Dialog", "Process..."))
self.label.setText(_translate("Dialog", "Files:" + str(noreports)))
self.pushButton.setText(_translate("Dialog", "Terminate"))
class Ui_Form(object):
def setupUi(self, Form):
Form.setObjectName("Form")
Form.resize(321, 247)
icon = QtGui.QIcon()
icon.addPixmap(QtGui.QPixmap("../../../../api-server/favicon.ico"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
Form.setWindowIcon(icon)
Form.setWindowOpacity(0.98)
Form.setProperty("sunrise", QtGui.QPixmap("../../../../api-server/ejemplo.png"))
self.lineEdit = QtWidgets.QLineEdit(Form)
self.lineEdit.setGeometry(QtCore.QRect(20, 130, 281, 51))
self.lineEdit.setAutoFillBackground(True)
self.lineEdit.setObjectName("lineEdit")
self.DescriptLbl = QtWidgets.QLabel(Form)
self.DescriptLbl.setGeometry(QtCore.QRect(20, 100, 281, 20))
self.DescriptLbl.setObjectName("DescriptLbl")
self.showinformBtn = QtWidgets.QPushButton(Form)
self.showinformBtn.setGeometry(QtCore.QRect(30, 190, 161, 31))
self.showinformBtn.setStyleSheet("background:rgb(110, 175, 255);\n"
"color:rgb(36, 36, 36);\n"
"border-radius:3px;\n"
"border-color:black;")
self.showinformBtn.setObjectName("showinformBtn")
self.dialogo = Dialogo()
self.showinformBtn.clicked.connect(self.abrirDialogo)
#self.showinformBtn.clicked.connect(self.showinform)
self.CancelarBtn = QtWidgets.QPushButton(Form)
self.CancelarBtn.setGeometry(QtCore.QRect(220, 190, 75, 31))
self.CancelarBtn.setStyleSheet("background:rgb(226, 76, 31);\n"
"color:rgb(36, 36, 36);\n"
"border-radius:3px;\n"
"border-color:black;")
self.CancelarBtn.setObjectName("CancelarBtn")
self.label_2 = QtWidgets.QLabel(Form)
self.label_2.setGeometry(QtCore.QRect(20, 220, 311, 20))
self.label_2.setTextFormat(QtCore.Qt.RichText)
self.label_2.setScaledContents(True)
self.label_2.setOpenExternalLinks(True)
self.label_2.setTextInteractionFlags(QtCore.Qt.LinksAccessibleByKeyboard|QtCore.Qt.LinksAccessibleByMouse|QtCore.Qt.TextBrowserInteraction|QtCore.Qt.TextEditable|QtCore.Qt.TextEditorInteraction|QtCore.Qt.TextSelectableByKeyboard|QtCore.Qt.TextSelectableByMouse)
self.label_2.setObjectName("label_2")
self.showinformLbl = QtWidgets.QLabel(Form)
self.showinformLbl.setGeometry(QtCore.QRect(20, 30, 281, 41))
font = QtGui.QFont()
font.setPointSize(22)
self.showinformLbl.setFont(font)
self.showinformLbl.setObjectName("showinformLbl")
self.imagen = QtWidgets.QLabel(Form)
self.imagen.setGeometry(QtCore.QRect(-80, 0, 221, 231))
self.imagen.setText("")
self.imagen.setPixmap(QtGui.QPixmap("max.png"))
self.imagen.setScaledContents(False)
self.imagen.setIndent(-1)
self.imagen.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
self.imagen.setObjectName("imagen")
self.imagen.raise_()
self.lineEdit.raise_()
self.DescriptLbl.raise_()
self.showinformBtn.raise_()
self.CancelarBtn.raise_()
self.label_2.raise_()
self.showinformLbl.raise_()
self.retranslateUi(Form)
QtCore.QMetaObject.connectSlotsByName(Form)
def retranslateUi(self, Form):
_translate = QtCore.QCoreApplication.translate
Form.setWindowTitle(_translate("Form", "api-server"))
self.lineEdit.setToolTip(_translate("Form", "<html><head/><body><p>write.</p></body></html>"))
self.lineEdit.setWhatsThis(_translate("Form", "<html><head/><body><p>write.</p></body></html>"))
self.DescriptLbl.setText(_translate("Form", "descrip inform."))
self.showinformBtn.setToolTip(_translate("Form", "<html><head/><body><p>Create report.</p></body></html>"))
self.showinformBtn.setText(_translate("Form", "show inform"))
self.CancelarBtn.setToolTip(_translate("Form", "<html><head/><body><p>Cancel.</p></body></html>"))
self.CancelarBtn.setText(_translate("Form", "Cancel"))
self.label_2.setText(_translate("Form", "<html><head/><body><p>Visit api-server. ;)</p></body></html>"))
self.showinformLbl.setText(_translate("Form", "show inform."))
def abrirDialogo(self):
nombreinform = self.lineEdit.text()
self.dialogo.nombre.setText('inform:' + nombreinform)
self.dialogo.show()
self.showinform()
def showinform(self):
current_time = datetime.datetime.today().strftime("%Y-%b-%dT%H_%M")
alle = glob.glob('*.txt')
counterfile = noreports
porcentotal = 0
suma = 100/counterfile
counterbien = 0
for file in alle:
porcentotal += float(suma)
avance = round(float(porcentotal), 0)
self.dialogo.progressBar.setProperty("value", format(avance))
self.dialogo.textEdit.setText(file + format(avance))
print ('{!r} %'.format(avance))
dict = '{!r} %'.format(avance)
f = open(file,'w')
f.write('result = ' + repr(dict) + '\n')
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
Form = QtWidgets.QWidget()
ui = Ui_Form()
ui.setupUi(Form)
Form.show()
sys.exit(app.exec_())
The code is executed but not displayed in Dialog, only the labels but not the progress bar.
Why does this happen?
The problem is that you are using the format function badly, this is used when you have a string and you want to insert data with a certain format.
The setProperty function requires as first parameter the property you want to assign, and a second value of the type that requires the property, in your case value requires an integer value so you can pass the percentage directly without needing to change it to string.
If you read many files this can block the main thread where the GUI is drawn, to solve this you must use QApplication.processEvents()
def showinform(self):
current_time = datetime.datetime.today().strftime("%Y-%b-%dT%H_%M")
alle = glob.glob('*.txt')
counterfile = noreports
porcentotal = 0
suma = 100/counterfile
counterbien = 0
for file in alle:
porcentotal += float(suma)
avance = round(float(porcentotal), 0)
self.dialogo.progressBar.setProperty("value", avance)
self.dialogo.textEdit.append("{}{}".format(file, avance))
print ('{!r} %'.format(avance))
dict = '{!r} %'.format(avance)
QApplication.processEvents()
f = open(file,'w')
f.write('result = ' + repr(dict) + '\n')
Note: I have changed the setText function to append in QTextEdit so that it is added and not overwritten.
Instead of using setProperty you could use the setValue function of QProgressBar:
self.dialogo.progressBar.setValue(avance)
Another recommendation is to verify that the counterfile is non-zero since it could generate an exception for the division.
I'm new to PyQt5 and want to code a small programm
I designed two Windows in QT Designer and convertet them into a py Script.
Afterwards i merged both into one file (maybe my attempt is totaly wrong - so pls correct me)
When the program starts I get a small Window with some Radio Buttons and OK and Cancel.
I want to start another Window by clicking on OK. (This works fine)
My problem is, that the initial Window stays active in Background. (How can I close only the initial window? all my attempts have closed the whole programm. I do not know what I have to change?
import sys
from PyQt5 import QtCore, QtGui, QtWidgets
class CLASS_WELCOME(object):
def setupUi(self, Welcome):
Welcome.setObjectName("Welcome")
Welcome.resize(204, 215)
Welcome.setWindowTitle("Welcome")
Welcome.setWhatsThis("")
self.buttonBox = QtWidgets.QDialogButtonBox(Welcome)
self.buttonBox.setGeometry(QtCore.QRect(0, 180, 191, 32))
self.buttonBox.setOrientation(QtCore.Qt.Horizontal)
self.buttonBox.setStandardButtons(QtWidgets.QDialogButtonBox.Cancel|QtWidgets.QDialogButtonBox.Ok)
self.buttonBox.setObjectName("buttonBox")
self.frame = QtWidgets.QFrame(Welcome)
self.frame.setGeometry(QtCore.QRect(20, 40, 151, 131))
self.frame.setFrameShape(QtWidgets.QFrame.StyledPanel)
self.frame.setFrameShadow(QtWidgets.QFrame.Raised)
self.frame.setObjectName("frame")
self.radioButton = QtWidgets.QRadioButton(self.frame)
self.radioButton.setGeometry(QtCore.QRect(10, 10, 116, 22))
self.radioButton.setObjectName("radioButton")
self.radioButton_2 = QtWidgets.QRadioButton(self.frame)
self.radioButton_2.setGeometry(QtCore.QRect(10, 40, 116, 22))
self.radioButton_2.setObjectName("radioButton_2")
self.radioButton_3 = QtWidgets.QRadioButton(self.frame)
self.radioButton_3.setGeometry(QtCore.QRect(10, 70, 116, 22))
self.radioButton_3.setObjectName("radioButton_3")
self.radioButton_4 = QtWidgets.QRadioButton(self.frame)
self.radioButton_4.setGeometry(QtCore.QRect(10, 100, 116, 22))
self.radioButton_4.setObjectName("radioButton_4")
self.label = QtWidgets.QLabel(Welcome)
self.label.setGeometry(QtCore.QRect(10, 10, 191, 17))
font = QtGui.QFont()
font.setBold(True)
font.setWeight(75)
self.label.setFont(font)
self.label.setObjectName("label")
self.retranslateUi(Welcome)
self.buttonBox.accepted.connect(self.onOK)
self.buttonBox.rejected.connect(Welcome.reject)
QtCore.QMetaObject.connectSlotsByName(Welcome)
self.Gui = CLASS_GUI()
def retranslateUi(self, Welcome):
_translate = QtCore.QCoreApplication.translate
self.radioButton.setText(_translate("Welcome", "blue"))
self.radioButton_2.setText(_translate("Welcome", "green"))
self.radioButton_3.setText(_translate("Welcome", "red"))
self.radioButton_4.setText(_translate("Welcome", "yellow"))
self.label.setText(_translate("Welcome", "Mensch aergere dich nicht!"))
def onOK(self):
MenschUi = QtWidgets.QDialog()
MenschUi.ui = CLASS_GUI()
MenschUi.ui.setupUi(MenschUi)
MenschUi.exec_()
class CLASS_GUI(object):
def setupUi(self, MenschUi):
MenschUi.setObjectName("MenschUi")
MenschUi.resize(640, 485)
self.Abbrechen = QtWidgets.QDialogButtonBox(MenschUi)
self.Abbrechen.setGeometry(QtCore.QRect(290, 450, 341, 32))
self.Abbrechen.setOrientation(QtCore.Qt.Horizontal)
self.Abbrechen.setStandardButtons(QtWidgets.QDialogButtonBox.Cancel)
self.Abbrechen.setCenterButtons(False)
self.Abbrechen.setObjectName("Abbrechen")
self.frame = QtWidgets.QFrame(MenschUi)
self.frame.setGeometry(QtCore.QRect(100, 10, 531, 431))
self.frame.setFrameShape(QtWidgets.QFrame.StyledPanel)
self.frame.setFrameShadow(QtWidgets.QFrame.Raised)
self.frame.setObjectName("frame")
self.Spieler = QtWidgets.QLabel(MenschUi)
self.Spieler.setGeometry(QtCore.QRect(10, 20, 66, 17))
self.Spieler.setObjectName("Spieler")
self.Computer = QtWidgets.QLabel(MenschUi)
self.Computer.setGeometry(QtCore.QRect(10, 100, 66, 17))
self.Computer.setObjectName("Computer")
self.LCDSpieler = QtWidgets.QLCDNumber(MenschUi)
self.LCDSpieler.setGeometry(QtCore.QRect(20, 40, 21, 23))
self.LCDSpieler.setDigitCount(1)
self.LCDSpieler.setObjectName("LCDSpieler")
self.LCDComputer = QtWidgets.QLCDNumber(MenschUi)
self.LCDComputer.setGeometry(QtCore.QRect(20, 130, 21, 23))
self.LCDComputer.setDigitCount(1)
self.LCDComputer.setObjectName("LCDComputer")
self.wuerfeln = QtWidgets.QPushButton(MenschUi)
self.wuerfeln.setGeometry(QtCore.QRect(10, 70, 81, 27))
self.wuerfeln.setObjectName("wuerfeln")
self.label = QtWidgets.QLabel(MenschUi)
self.label.setGeometry(QtCore.QRect(10, 450, 491, 21))
self.label.setText("")
self.label.setObjectName("label")
self.retranslateUi(MenschUi)
self.Abbrechen.accepted.connect(MenschUi.accept)
self.Abbrechen.rejected.connect(MenschUi.reject)
self.wuerfeln.clicked.connect(MenschUi.open)
QtCore.QMetaObject.connectSlotsByName(MenschUi)
def retranslateUi(self, MenschUi):
_translate = QtCore.QCoreApplication.translate
MenschUi.setWindowTitle(_translate("MenschUi", "Mensch Aergere dich Nicht!"))
self.Spieler.setText(_translate("MenschUi", "Spieler"))
self.Computer.setText(_translate("MenschUi", "Computer"))
self.wuerfeln.setText(_translate("MenschUi", "wuerfeln"))
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
Welcome = QtWidgets.QDialog()
ui = CLASS_WELCOME()
ui.setupUi(Welcome)
Welcome.show()
sys.exit(app.exec_())
Possibly calling self.hide() in the beginning of the method onOK would do the job. (Untested)
You could lookup some Methods here.