Writing cleaner code
-
I did post something similar recently but I think either I was very unclear or I was asking for too much or, possibly, maybe I was thought to being lazy.
Anyway, what I want to do, if possible, is learn to code using QT more effectively, more elegantly. I have the book, use this forum and the online resources but I still walk away with some confusions, or feelings that things could be better.
Let me explain; a section of my code is this...
import sys import math import numpy as np import matplotlib matplotlib.use('Qt5Agg') from PyQt6.QtCore import Qt, QSize from PyQt6.QtWidgets import (QApplication, QMainWindow, QWidget, QVBoxLayout) from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FCQTA, NavigationToolbar2QT as NTbar from matplotlib.figure import Figure def convert(oldValue): ---- SHOULD THIS FUNCTION BE MOVED TO INSIDE THE MAINWINDOW CLASS? return newValue def readData(datafile): ---- SHOULD THIS FUNCTION BE MOVED TO INSIDE THE MAINWINDOW CLASS? return data class MplCanvas(FCQTA): def __init__(self, parent=None, width=5, height=4, dpi=100): fig = Figure(figsize=(width, height), dpi=dpi) self.axs = fig.add_subplot(111) super(MplCanvas, self).__init__(fig) class MainWindow(QMainWindow): def __init__(self): ---------CODE HERE---------- sc = MplCanvas(self, width=5, height=4, dpi=100) for index, filename in enumerate(filenames): stellarData = readData(filename) colour = colours[index % 7] line = lines[index // 7] ---------CODE HERE---------- self.show() if __name__ == "__main__": ---------CODE HERE----------Since the two functions are only used within the
mainWindowclass, should I move those into there and, if so, how would I reference them in the code?Then...
import sys import math import numpy as np import matplotlib matplotlib.use('Qt5Agg') from PyQt6.QtCore import Qt, QSize from PyQt6.QtWidgets import ( QApplication, QMainWindow, QWidget, QVBoxLayout, ) from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FCQTA, NavigationToolbar2QT as NTbar from matplotlib.figure import Figure def convert(oldValue): ---- SOME CODE HERE ---- return newValue def readData(datafile): ----SOME CODE HERE ---- return data class MplCanvas(FCQTA): def __init__(self, parent=None, width=5, height=4, dpi=100): fig = Figure(figsize=(width, height), dpi=dpi) self.axs = fig.add_subplot(111) super(MplCanvas, self).__init__(fig) class MainWindow(QMainWindow): def __init__(self): super(MainWindow, self).__init__() ########## HERE 1 ######## SIGMA = 5.67051e-5 PI = math.pi M_SUN = 1.989e33 L_SUN = 3.826e33 R_SUN = 6.9599e10 YEAR = 3.15570e7 sa_sun = 4 * PI * math.pow(R_SUN, 2) t_sun = L_SUN / (sa_sun * SIGMA) filenames = ["dummy0.5.lst", "dummy1.lst", "dummy2.lst", "dummy5.lst", "dummy10.lst", "dummy20.lst"] colours = ['r', 'g', 'b', 'c', 'm', 'y', 'k'] lines = ['solid', 'dotted', 'dashed', 'dashdot'] ########## END HERE 1 ######## self.setWindowTitle("StelCor") self.setFixedSize(QSize(1024, 768)) sc = MplCanvas(self, width=5, height=4, dpi=100) for index, filename in enumerate(filenames): stellarData = readData(filename) colour = colours[index % 7] line = lines[index // 7] ############## HERE 2 ############# l_star = stellarData[:, 4] / L_SUN r_star = np.power(stellarData[:, 3] / R_SUN, 2) t_star = np.power((t_sun * l_star) / r_star, 0.25) sc.axs.loglog(t_star[:], l_star[:], color=colour, linestyle=line, label=filename) sc.axs.set_title(r'Temperature Magnitude (TM) Diagram') sc.axs.set_xlabel(r'Surface Temperature (Kelvin) - ${(\frac{t_{\odot} \times L_{\star}}{R_{\odot}})}^\frac{1}{4}$') sc.axs.set_ylabel(r'Luminosity (Solar Units) - $\frac{L_{\star}}{L_{\odot}}$') ############## END HERE 2 ############# sc.axs.invert_xaxis() sc.axs.legend() tb = NTbar(sc, self) layout = QVBoxLayout() layout.addWidget(tb) layout.addWidget(sc) ############## OR END HERE 2 ############# widget = QWidget() widget.setLayout(layout) self.setCentralWidget(widget) self.show() if __name__ == "__main__": --------- SOME CODE HERE ---------The graphing code (the code that generates my graph) is shown from HERE 2. HERE 1 marks the setting of values that are only used to generate the graphs.
Should I move all of this into MPLCanvas and, if so, how?
Or is there someone here that is willing to give me a little time to help coach me through this system?
-
Hi,
Shouldn't you create a new MplCanvas object for each file ? Here you are overwriting the content of the object on each iteration.
Also, since you want to make it cleaner, do not call ˋself.show`. It's not the role of the widget to show itself. It's the role of the controlling code to know when to show it.
-
Hi,
Shouldn't you create a new MplCanvas object for each file ? Here you are overwriting the content of the object on each iteration.
Also, since you want to make it cleaner, do not call ˋself.show`. It's not the role of the widget to show itself. It's the role of the controlling code to know when to show it.
@SGaist
I want the results of each file to be plotted on a single plot; the result I have does this - though, I am not sure this is the most efficient. As I say, the QT information is... unclear.I followed an example code here for the
.show. So, I moved theself.show()to the__main__section and made itw.show(); sure enough, this worked fine - thank you. That makes sense. Each of the classes defines the object; it is up to the object to declare when and where it appears - right? -
I am not sure I am following you correctly.
The core idea is that
self.show()is a no go especially in constructors (or in the case of Python the__init__function).