El logro de la alineación de los objetos dentro de la ventana, la adición de gráficos a partir de otro archivo .py

Josh E.:

Por lo tanto, me gustaría preguntarle acerca de una mejor organización de múltiples buttons, TextBox, gráficos en PyQt5. Anteriormente, he sido ayudado un poco para utilizar una cuadrícula para lograr una mejor alineación del objeto que he puesto en My Window.

Sin embargo, el final Estoy tratando de código es todavía un poco lejos de suceder.

Esto es lo que tengo hasta el momento:

from PyQt5 import QtWidgets, QtCore
from PyQt5.QtWidgets import *
import sys


class Okno(QMainWindow):
    def __init__(self):
        super(Okno, self).__init__()
        self.setGeometry(500, 500, 900, 500)
        self.setWindowTitle("My window")
        self.button1 = QtWidgets.QPushButton()
        self.button2 = QtWidgets.QPushButton()
        self.TextBox1 = QLineEdit(self)  # Parameter self - add text box to my Window "Okno"
        self.TextBox2 = QLineEdit(self)
        self.TextBox3 = QLineEdit(self)
        self.TextBox4 = QLineEdit(self)   # Baudrate
        self.TextBox5 = QLineEdit(self)   # Parity
        self.TB_TEMP_IN = QLineEdit(self)   # Temp_IN
        self.TB_TEMP_OUT = QLineEdit(self)   # Temp_OUT
        self.label1 = QtWidgets.QLabel()  # TextBox1, pressure_IN
        self.label2 = QtWidgets.QLabel()
        self.label3 = QtWidgets.QLabel()
        self.label4 = QtWidgets.QLabel()  # TextBox3, pressure_OUT
        self.label_TEMP_IN = QtWidgets.QLabel()
        self.label_TEMP_OUT = QtWidgets.QLabel()
        self.iniUI()

    # Window objects
    def iniUI(self):
        w = QtWidgets.QWidget()
        self.setCentralWidget(w)
        grid = QtWidgets.QGridLayout(w)

        self.button1.setText("Open file")
        self.button1.setMinimumWidth(150)
        self.button1.clicked.connect(self.open_file)
        self.button2.setText("Exit")
        self.button2.clicked.connect(self.close)

        grid.addWidget(self.button1, 10, 0, QtCore.Qt.AlignLeft | QtCore.Qt.AlignBottom)
        grid.addWidget(self.button2, 10, 6, QtCore.Qt.AlignRight | QtCore.Qt.AlignBottom)

        # Text Box
        grid.addWidget(self.TextBox1, 3, 1, QtCore.Qt.AlignCenter | QtCore.Qt.AlignCenter)

        self.TextBox2.setPlaceholderText("Enter port name")
        grid.addWidget(self.TextBox2, 3, 3, QtCore.Qt.AlignCenter | QtCore.Qt.AlignTop)

        grid.addWidget(self.TextBox3, 3, 6, QtCore.Qt.AlignLeft | QtCore.Qt.AlignCenter)

        self.TextBox4.setPlaceholderText("Baudrate")
        grid.addWidget(self.TextBox4, 3, 3, QtCore.Qt.AlignCenter | QtCore.Qt.AlignCenter)

        self.TextBox5.setPlaceholderText("Parity")
        grid.addWidget(self.TextBox5, 3, 3, QtCore.Qt.AlignCenter | QtCore.Qt.AlignBottom)

        grid.addWidget(self.TB_TEMP_IN, 3, 1, QtCore.Qt.AlignCenter | QtCore.Qt.AlignBottom)
        grid.addWidget(self.TB_TEMP_OUT, 3, 6, QtCore.Qt.AlignCenter | QtCore.Qt.AlignBottom)

        # Label (Text Box name)
        self.label1.setText("Pressure_IN")
        grid.addWidget(self.label1, 3, 0, QtCore.Qt.AlignRight| QtCore.Qt.AlignCenter)

        self.label4.setText("Pressure_OUT")
        grid.addWidget(self.label4, 3, 5, QtCore.Qt.AlignRight | QtCore.Qt.AlignCenter)

        self.label_TEMP_IN.setText("Temp_IN")
        grid.addWidget(self.label_TEMP_IN, 3, 0, QtCore.Qt.AlignRight| QtCore.Qt.AlignBottom)

        self.label_TEMP_OUT.setText("Temp_OUT")
        grid.addWidget(self.label_TEMP_OUT, 3, 5, QtCore.Qt.AlignRight | QtCore.Qt.AlignBottom)

        self.label2.setText("Data Input")
        grid.addWidget(self.label2, 0, 0, QtCore.Qt.AlignLeft | QtCore.Qt.AlignTop)
        self.label2.setStyleSheet('color: red')

        self.label3.setText("Data output")
        grid.addWidget(self.label3, 0, 6, QtCore.Qt.AlignRight | QtCore.Qt.AlignTop)
        self.label3.setStyleSheet('color: blue')

    def open_file(self):
        print("Open file")


def window():
    app = QApplication(sys.argv)
    okno = Okno()
    okno.show()
    sys.exit(app.exec_())


window()

Una cosa que he notado al tiempo que añade más objetos utilizando Grides que es difícil conseguirlo organizado. Tuve que ampliar la red de 10 x 6 si he entendido bien cómo funciona, pero la alineación (izquierda, centro, derecha) no ordena el objeto con el fin alineado como filas / columnas definidas por límites absolutos.

En cuanto a los eventos para los botones, cuadros de texto, ... yo debería ser capaz de programarlos, sólo que no tengo muchos con experiencia en la aplicación de Windows, mientras que en su mayoría haciendo aplicaciones de consola.

Sin embargo, ¿cómo debo añadir dos gráficos en My Window? Los estoy trazando en otro archivo .py usando matplotlib.pyplot, que parte de carga de los datos de los archivos .xls utilizando pandas y otra (salida de datos) serán recibidos en cualquiera de serie ( RS232 ) o TCP / IP de la interfaz. Tengo que trazarlos en el tiempo real, así como ser capaz de almacenarlos (como .txt o .csv, que realmente no importa).

¿Me podría dar algunas pistas acerca de cómo elegir el concepto correcto de mi ventana para lograr el ejemplo que he adjuntado a continuación y sea capaz de “facilidad” agregar otros objetos en el futuro si es necesario.

Definitivamente creo que las más objetos están en la ventana, se necesita una mejor organización, porque ambos: el método iniUI(self)y la clase Okno(QMainWindow)están bastante larga.

He hecho una simple ilustración de lo que estoy tratando de lograr:

introducir descripción de la imagen aquí

musicamante :

Ajuste de la alineación de widgets cuando los añade a la disposición no tiene efecto sobre la alineación de widgets, pero sólo en su alineamiento dentro del espacio de la disposición les proporciona. Además, muchos widgets automáticamente tratará de ampliar a sí mismos (como QLabels o vistas de elementos).

Por ejemplo, un QLabel tiene una alineación predeterminada izquierda / verticalmente centrada en el texto, por lo que es necesario establecer que la alineación, pero aún así tratará de ampliar su espacio disponible si otros widgets permiten.

To get what you need, you'll have to consider spacing between widgets, their sizePolicy (which represents the widget's "willingness" about its size when used in a layout, should it have a fixed size, can it grow/expand, can it be shrunk, etc).

Since you want some space between the columns, the most simple thing to do is to leave empty columns in the layout, and set a stretch factor on those columns using setColumnStretch() so that they will try to expand as much as possible.

Finally, for complex structures, it's always better to use nested layouts, meaning that you'll have a main layout set for the widget, and "child" layouts are added to it, so that each "section" has its own layout manager, independent from the others. In the following example I've implemented the structure like this:

    +-------------- main vertical layout ---------------+
    |                                                   |
    |  +------------ button grid layout -------------+  |
    |  |title|    |(empty)|      |(empty)|     |title|  |
    |  +-----+----+-------+------+-------+-----+-----+  |
    |  |label|edit|       |input |       |label|edit |  |
    |  +-----+----+-------+------+-------+-----+-----+  |
    |  |label|edit|       |input |       |label|edit |  |
    |  +-----+----+-------+------+-------+-----+-----+  |
    |  |label|edit|       |input |       |label|edit |  |
    |  +-----+----+-------+------+-------+-----+-----+  |
    +---------------------------------------------------+
    |                                                   |
    |  +---------- graph horizontal layout ----------+  |
    |  |                      |                      |  |
    |  |       left graph     |      right graph     |  |
    |  |                      |                      |  |
    |  +----------------------+----------------------+  |
    +---------------------------------------------------+
    |                                                   |
    |  +--------- button horizontal layout ----------+  |
    |  |        |                           |        |  |
    |  | button |         (stretch)         | button |  |
    |  |        |                           |        |  |
    |  +--------+---------------------------+--------+  |
    +---------------------------------------------------+ 

Here's how it appears:

captura de pantalla de la disposición

And this is the code. Note that I removed widget creation from the init (if you use an initUi function it doesn't make a lot of sense that you create them elsewhere).

from PyQt5 import QtWidgets, QtCore
from matplotlib.figure import Figure
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
import sys


class Okno(QtWidgets.QMainWindow):
    def __init__(self):
        super(Okno, self).__init__()
        self.setGeometry(500, 500, 900, 500)
        self.setWindowTitle("My window")
        self.iniUI()

    def iniUI(self):
        w = QtWidgets.QWidget()
        self.setCentralWidget(w)

        mainLayout = QtWidgets.QVBoxLayout(w)

        grid = QtWidgets.QGridLayout()
        mainLayout.addLayout(grid)

        self.dataInputLabel = QtWidgets.QLabel('Data Input')
        grid.addWidget(self.dataInputLabel, 0, 0)
        self.dataInputLabel.setStyleSheet('color: red')

        portSettingLabel = QtWidgets.QLabel('Port setting', alignment=QtCore.Qt.AlignCenter)
        grid.addWidget(portSettingLabel, 0, 3)

        self.dataOutputLabel = QtWidgets.QLabel('Data Output', alignment=QtCore.Qt.AlignRight|QtCore.Qt.AlignVCenter)
        grid.addWidget(self.dataOutputLabel, 0, 6)
        self.dataOutputLabel.setStyleSheet('color: blue')

        # set the vertical policy to Maximum for labels, so they don't try to
        # expand themselves if there's more available space
        for label in (self.dataInputLabel, portSettingLabel, self.dataOutputLabel):
            label.setSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Maximum)

        grid.addWidget(QtWidgets.QLabel('Pressure [kPa]'), 1, 0)
        self.inputPressure = QtWidgets.QLineEdit(readOnly=True)
        grid.addWidget(self.inputPressure, 1, 1)

        grid.addWidget(QtWidgets.QLabel('Temperature [K]'), 2, 0)
        self.inputTemp = QtWidgets.QLineEdit(readOnly=True)
        grid.addWidget(self.inputTemp, 2, 1)

        grid.addWidget(QtWidgets.QLabel('Humidity [%]'), 3, 0)
        self.inputHumidity = QtWidgets.QLineEdit(readOnly=True)
        grid.addWidget(self.inputHumidity, 3, 1)

        self.portEdit = QtWidgets.QLineEdit(placeholderText='Enter port')
        grid.addWidget(self.portEdit, 1, 3)
        self.baudEdit = QtWidgets.QLineEdit(placeholderText='Baudrate')
        grid.addWidget(self.baudEdit, 2, 3)
        self.parityEdit = QtWidgets.QLineEdit(placeholderText='Parity')
        grid.addWidget(self.parityEdit, 3, 3)

        grid.addWidget(QtWidgets.QLabel('Pressure [kPa]'), 1, 5)
        self.outputPressure = QtWidgets.QLineEdit(readOnly=True)
        grid.addWidget(self.outputPressure, 1, 6)

        grid.addWidget(QtWidgets.QLabel('Temperature [K]'), 2, 5)
        self.outputTemp = QtWidgets.QLineEdit(readOnly=True)
        grid.addWidget(self.outputTemp, 2, 6)

        grid.addWidget(QtWidgets.QLabel('Humidity [%]'), 3, 5)
        self.outputHumidity = QtWidgets.QLineEdit(readOnly=True)
        grid.addWidget(self.outputHumidity, 3, 6)

        grid.setColumnStretch(2, 1)
        grid.setColumnStretch(4, 1)

        graphLayout = QtWidgets.QHBoxLayout()
        mainLayout.addLayout(graphLayout)
        # here insert your graphs...
        self.graphLeft = FigureCanvas(Figure())
        graphLayout.addWidget(self.graphLeft)
        self.graphRight = FigureCanvas(Figure())
        graphLayout.addWidget(self.graphRight)

        buttonLayout = QtWidgets.QHBoxLayout()
        mainLayout.addLayout(buttonLayout)

        self.openButton = QtWidgets.QPushButton('Open file')
        self.openButton.setMinimumWidth(150)
        self.openButton.clicked.connect(self.open_file)
        buttonLayout.addWidget(self.openButton)

        # add an empty "stretch", which acts as an expanding spacer on box layouts
        buttonLayout.addStretch()

        self.exitButton = QtWidgets.QPushButton('Exit')
        self.exitButton.clicked.connect(self.close)
        buttonLayout.addWidget(self.exitButton)

Por último, considere el uso de Qt Designer, que es útil para la creación de diseños complejos (o, al menos, visualizarlos mientras estás en el proceso de diseño de los mismos, si todavía quiere hacer todo por código). Nótese que en este caso debe seguir las directrices sugeridas en el Diseñador (lo más importante, nunca se edite los archivos pitón generados con la pyuicutilidad), o el uso loadUi('yourguifile.ui', self)(donde selfestá el widget / ventana que desea configurar con la interfaz de usuario) desde el PyQt5.uicmódulo .

Supongo que te gusta

Origin http://10.200.1.11:23101/article/api/json?id=377751&siteId=1
Recomendado
Clasificación