0

I'm trying to complete a GUI in python using PyQt5 (without using PySide2 due to problems with some drivers). It happens that the part of the window that should contain the graph does not appear in the designated location.

I already tried to implement this GUI using the layout method (GUI using layout method in Qt5), which worked, but the location of the widgets was chosen by the method, so to get the GUI like the image below (the desired GUI), I used the setGeometry method, with which I got the same GUI I had in mind when I designed it using QtDesigner.

To help you understand this problem, below is a short description of how the program works:
The program consists of a single window containing the graph(which shows the data selected and a polynomial fit); buttons on the right side of the window (these buttons are controllable and updates de polynomial_fit when they are modified); a button to open the dialogWindow (Finder window or windows_file_explorer) and a field that indicate the path of the chosen file; a button to exit the program. That's all that the program does for now.

Below is the code I wrote in Python3.7 using Qt5 that produces the GUI in the image (The GUI with problem ):

import sys
import numpy as np
import matplotlib.pyplot as plt
from PyQt5.QtWidgets import QApplication, QMainWindow, QFileDialog, QPushButton
from PyQt5.QtWidgets import QWidget, QLabel, QTextBrowser, QDoubleSpinBox, QPlainTextEdit
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from scipy.optimize import curve_fit



# Função de ajuste
def fit_function(x, a1, a2, a3, Ea1, Ea2):
    KbT = 1.0
    return a1 * np.exp(-Ea1 / (KbT * x)) + a2 * np.exp(-Ea2 / (KbT * x)) + a3


class LabfitApp(QMainWindow):

    def __init__(self):
        super().__init__()
        self.setWindowTitle('LabFit - Photoluminescence')
        self.setGeometry(170, 10, 271, 41)
        self.data = None
        self.init_ui()

    def open_file_dialog(self):
        options = QFileDialog.Options()
        file_dialog = QFileDialog()
        selected_file, _ = file_dialog.getOpenFileName(self, 'Selecione um Arquivo', '', 'Todos os Arquivos (*);;Text Files (*.txt);;CSV Files (*.csv);;Output Files (*.out)', options=options)

        if selected_file:
            self.plainTextEdit.setPlainText(selected_file)  # Define o texto no campo de entrada
            try:
                self.data = np.loadtxt(selected_file)
                self.textBrowser.clear()
                self.update_plot()
            except Exception as e:
                self.textBrowser.setPlainText(f"Erro ao carregar arquivo: {str(e)}")
        else:
            self.data = np.genfromtxt(str(input()), delimiter=',')

    def init_ui(self):
        central_widget = QWidget(self)
        self.setCentralWidget(central_widget)
        self.setGeometry(100, 100, 791, 630)

        # Definindo geometria dos widgets
        self.textBrowser = QTextBrowser(self)
        self.textBrowser.setGeometry(170, 10, 261, 41)
        self.textBrowser.setHtml('<span style="font-size:18pt; font-weight:600; color:#910039;">LabFit - Photoluminescence</span>')

        file_label = QLabel('File path:', self)
        file_label.setGeometry(20, 530, 61, 31)

        self.plainTextEdit = QPlainTextEdit(self)
        self.plainTextEdit.setGeometry(90, 530, 400, 30)

        self.pushButton = QPushButton('Exit', self)
        self.pushButton.setGeometry(670, 550, 113, 32)
        self.pushButton.clicked.connect(self.close)

        labels = ['a1:', 'a2:', 'a3:', 'Ea1:', 'Ea2:']
        self.doubleSpinBoxes = []

        for i, label in enumerate(labels):
            spin_box = QDoubleSpinBox(self)
            spin_box.setGeometry(710, 180 + i * 40, 62, 22)
            label_widget = QLabel(label, self)
            label_widget.setGeometry(660, 180 + i * 40, 100, 30)
            self.doubleSpinBoxes.append(spin_box)
            # Conecta a alteração de valor ao método de atualização
            spin_box.valueChanged.connect(self.update_plot)

        self.pushButton_2 = QPushButton('Open File', self)
        self.pushButton_2.setGeometry(500, 530, 113, 32)
        self.pushButton_2.clicked.connect(self.open_file_dialog)

        # Criando a figura separadamente
        # O widget responsável por criar um quadrado para exibição do plot.
        # self.graphicsView = FigureCanvas(plt.figure(figsize=(8, 4)))
        # layout.addWidget(self.graphicsView)                             # Aqui esse widget é adicionado à janela (o layout).
        self.figure = plt.figure(figsize=(8, 6))
        self.graphicsView = FigureCanvas(self.figure)
        self.graphicsView.setGeometry(100, 100, 800, 600)

    def update_plot(self):
        if self.data is not None:
            x = np.arange(len(self.data))
            params = [spin_box.value() for spin_box in self.doubleSpinBoxes]
            y_fit = fit_function(x, *params)

            self.graphicsView.figure.clear()
            ax = self.graphicsView.figure.add_subplot(111)
            ax.plot(x, self.data, '-', label='Dados')
            ax.plot(x, y_fit, label=f'Ajuste')
            ax.set_xlabel('Índice')
            ax.set_ylabel('Valor')
            ax.legend()
            ax.set_title('Ajuste Polinomial')

            self.graphicsView.draw()


def main():
    app = QApplication(sys.argv)
    window = LabfitApp()
    window.show()
    sys.exit(app.exec_())


if __name__ == '__main__':
    main()

• Below is the python code generated from the QtDesigner .ui file (this code uses PySide2, which is a package incompatible with my OS):

# -*- coding: utf-8 -*-

################################################################################
## Form generated from reading UI file 'main_windowhbupzW.ui'
##
## Created by: Qt User Interface Compiler version 5.15.0
##
## WARNING! All changes made in this file will be lost when recompiling UI file!
################################################################################

from PySide2.QtCore import (QCoreApplication, QDate, QDateTime, QMetaObject,
    QObject, QPoint, QRect, QSize, QTime, QUrl, Qt)
from PySide2.QtGui import (QBrush, QColor, QConicalGradient, QCursor, QFont,
    QFontDatabase, QIcon, QKeySequence, QLinearGradient, QPalette, QPainter,
    QPixmap, QRadialGradient)
from PySide2.QtWidgets import *


class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        if not MainWindow.objectName():
            MainWindow.setObjectName(u"MainWindow")
        MainWindow.resize(792, 630)
        self.centralwidget = QWidget(MainWindow)
        self.centralwidget.setObjectName(u"centralwidget")
        self.textBrowser = QTextBrowser(self.centralwidget)
        self.textBrowser.setObjectName(u"textBrowser")
        self.textBrowser.setGeometry(QRect(620, 60, 161, 31))
        self.doubleSpinBox = QDoubleSpinBox(self.centralwidget)
        self.doubleSpinBox.setObjectName(u"doubleSpinBox")
        self.doubleSpinBox.setGeometry(QRect(710, 120, 62, 22))
        self.doubleSpinBox_2 = QDoubleSpinBox(self.centralwidget)
        self.doubleSpinBox_2.setObjectName(u"doubleSpinBox_2")
        self.doubleSpinBox_2.setGeometry(QRect(710, 160, 62, 22))
        self.doubleSpinBox_3 = QDoubleSpinBox(self.centralwidget)
        self.doubleSpinBox_3.setObjectName(u"doubleSpinBox_3")
        self.doubleSpinBox_3.setGeometry(QRect(710, 200, 62, 22))
        self.doubleSpinBox_4 = QDoubleSpinBox(self.centralwidget)
        self.doubleSpinBox_4.setObjectName(u"doubleSpinBox_4")
        self.doubleSpinBox_4.setGeometry(QRect(710, 240, 62, 22))
        self.doubleSpinBox_5 = QDoubleSpinBox(self.centralwidget)
        self.doubleSpinBox_5.setObjectName(u"doubleSpinBox_5")
        self.doubleSpinBox_5.setGeometry(QRect(710, 280, 62, 22))
        self.plainTextEdit = QPlainTextEdit(self.centralwidget)
        self.plainTextEdit.setObjectName(u"plainTextEdit")
        self.plainTextEdit.setGeometry(QRect(90, 530, 401, 31))
        self.label = QLabel(self.centralwidget)
        self.label.setObjectName(u"label")
        self.label.setGeometry(QRect(20, 530, 61, 31))
        self.pushButton = QPushButton(self.centralwidget)
        self.pushButton.setObjectName(u"pushButton")
        self.pushButton.setGeometry(QRect(670, 550, 113, 32))
        self.label_2 = QLabel(self.centralwidget)
        self.label_2.setObjectName(u"label_2")
        self.label_2.setGeometry(QRect(660, 120, 20, 21))
        self.label_3 = QLabel(self.centralwidget)
        self.label_3.setObjectName(u"label_3")
        self.label_3.setGeometry(QRect(660, 160, 21, 21))
        self.label_4 = QLabel(self.centralwidget)
        self.label_4.setObjectName(u"label_4")
        self.label_4.setGeometry(QRect(660, 200, 20, 20))
        self.label_5 = QLabel(self.centralwidget)
        self.label_5.setObjectName(u"label_5")
        self.label_5.setGeometry(QRect(660, 280, 21, 21))
        self.label_6 = QLabel(self.centralwidget)
        self.label_6.setObjectName(u"label_6")
        self.label_6.setGeometry(QRect(660, 240, 21, 21))
        self.pushButton_2 = QPushButton(self.centralwidget)
        self.pushButton_2.setObjectName(u"pushButton_2")
        self.pushButton_2.setGeometry(QRect(500, 530, 113, 32))
        self.textBrowser_2 = QTextBrowser(self.centralwidget)
        self.textBrowser_2.setObjectName(u"textBrowser_2")
        self.textBrowser_2.setGeometry(QRect(170, 10, 271, 41))
        self.graphicsView_2 = QGraphicsView(self.centralwidget)
        self.graphicsView_2.setObjectName(u"graphicsView_2")
        self.graphicsView_2.setGeometry(QRect(30, 60, 569, 439))
        MainWindow.setCentralWidget(self.centralwidget)
        self.statusbar = QStatusBar(MainWindow)
        self.statusbar.setObjectName(u"statusbar")
        MainWindow.setStatusBar(self.statusbar)
        QWidget.setTabOrder(self.textBrowser_2, self.pushButton_2)
        QWidget.setTabOrder(self.pushButton_2, self.plainTextEdit)
        QWidget.setTabOrder(self.plainTextEdit, self.textBrowser)
        QWidget.setTabOrder(self.textBrowser, self.doubleSpinBox)
        QWidget.setTabOrder(self.doubleSpinBox, self.doubleSpinBox_2)
        QWidget.setTabOrder(self.doubleSpinBox_2, self.doubleSpinBox_3)
        QWidget.setTabOrder(self.doubleSpinBox_3, self.doubleSpinBox_4)
        QWidget.setTabOrder(self.doubleSpinBox_4, self.doubleSpinBox_5)
        QWidget.setTabOrder(self.doubleSpinBox_5, self.pushButton)

        self.retranslateUi(MainWindow)

        QMetaObject.connectSlotsByName(MainWindow)
    # setupUi

    def retranslateUi(self, MainWindow):
        MainWindow.setWindowTitle(QCoreApplication.translate("MainWindow", u"MainWindow", None))
        self.textBrowser.setHtml(QCoreApplication.translate("MainWindow", u"<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n"
"<html><head><meta name=\"qrichtext\" content=\"1\" /><style type=\"text/css\">\n"
"p, li { white-space: pre-wrap; }\n"
"</style></head><body style=\" font-family:'.SF NS Text'; font-size:13pt; font-weight:400; font-style:normal;\">\n"
"<p align=\"center\" style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-weight:600; color:#264eac;\">Fit Parameters Control</span></p></body></html>", None))
        self.label.setText(QCoreApplication.translate("MainWindow", u"File path:", None))
        self.pushButton.setText(QCoreApplication.translate("MainWindow", u"Exit", None))
        self.label_2.setText(QCoreApplication.translate("MainWindow", u"a1:", None))
        self.label_3.setText(QCoreApplication.translate("MainWindow", u"a2:", None))
        self.label_4.setText(QCoreApplication.translate("MainWindow", u"a3:", None))
        self.label_5.setText(QCoreApplication.translate("MainWindow", u"Ea2:", None))
        self.label_6.setText(QCoreApplication.translate("MainWindow", u"Ea1:", None))
        self.pushButton_2.setText(QCoreApplication.translate("MainWindow", u"Open File", None))
        self.textBrowser_2.setHtml(QCoreApplication.translate("MainWindow", u"<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n"
"<html><head><meta name=\"qrichtext\" content=\"1\" /><style type=\"text/css\">\n"
"p, li { white-space: pre-wrap; }\n"
"</style></head><body style=\" font-family:'.SF NS Text'; font-size:13pt; font-weight:400; font-style:normal;\">\n"
"<p align=\"center\" style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-size:18pt; font-weight:600; color:#910039;\">LabFit - Photoluminescence</span></p></body></html>", None))
    # retranslateUi

The interface worked, but the widgets were out of the desired locations. So I replaced the layout method with setGeometry, with which I would have control over the position of the widgets. It turns out that the graph was no longer displayed in the window, even when changing its position with setGeometry.

Furthermore, after selecting the desired data file, the text at the top of the window (a title) simply disappeared and was left with a blank space (as can be seen here: GUI after file selection ).

0

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.