Alcançar o alinhamento de objetos dentro da janela, adicionando gráficos de outro arquivo .py

Josh E.:

Então, eu gostaria de lhe perguntar sobre melhor múltipla organizar buttons, TextBox, Gráficos em PyQt5. Anteriormente, eu tenho ajudado um pouco de usar uma grade para conseguir um melhor alinhamento do objeto que eu colocar My Window.

No entanto, o final Eu estou tentando código ainda é um pouco longe de acontecer.

Aqui está o que eu tenho até agora:

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()

Uma coisa que tenho notado ao adicionar mais objetos usando Gridé que é difícil obtê-lo organizado. Eu tinha que expandir o grid para 10 x 6 se eu entendi como ele funciona, mas o alinhamento (esquerda, centro, direita) não classifica o objeto de forma alinhada, como linhas / colunas definidas por limites absolutos.

Quanto aos eventos para os botões, caixas de texto, ... Eu deveria ser capaz de programá-los, eu simplesmente não têm muitas experiência com aplicativo Windows enquanto na maior parte fazendo aplicações de console.

No entanto, como devo adicionar dois gráficos em My Window? Eu estou traçando-los em outro arquivo .py usando matplotlib.pyplot, eu parte da carga dos dados de arquivos .xls usando pandas e outro (saída de dados) serão recebidas sobre qualquer série ( RS232 ) ou TCP / IP interface. Eu tenho que traçar-los no tempo real, bem como ser capaz de armazená-los (como .txt ou .csv, ele realmente não importa).

Você poderia me dar algumas dicas sobre como escolher o conceito certo de minha janela para alcançar o exemplo Anexei abaixo e ser capaz de “facilmente” adicionar outros objetos no futuro, se necessário.

Eu definitivamente acho que quanto mais objetos estão na janela, a melhor organização é necessário, porque ambos: método iniUI(self)e classe Okno(QMainWindow)estão ficando muito longa.

Fiz uma ilustração simples do que eu estou tentando alcançar:

digite descrição da imagem aqui

musicamante:

Definir o alinhamento de widgets quando adicioná-los à disposição não tem efeito sobre o alinhamento widget, mas apenas em seu alinhamento dentro do espaço do layout proporciona-lhes. Além disso, muitos widgets automaticamente tentar expandir-se (como QLabels ou vistas de itens).

Por exemplo, um QLabel tem um alinhamento padrão esquerdo / centralizado verticalmente para o texto, então você precisa definir que o alinhamento, mas ainda vai tentar expandir seu espaço disponível, se outros widgets permitem.

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:

imagem do layout

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)

Finalmente, considere o uso Qt Designer, que é útil para criar layouts complexos (ou, pelo menos, visualizá-los quando você estiver no processo de projetá-los, se você ainda quer fazer tudo por código). Note-se que, neste caso, você deve seguir as orientações sugeridas no utilizando Designer (o mais importante, não editar os arquivos python gerados com o pyuicutilitário), ou uso loadUi('yourguifile.ui', self)(onde selfé widget / janela que você deseja configurar com o UI) do PyQt5.uicmódulo .

Acho que você gosta

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