PyQt5从多个Qwidget中读取值并转换为类

时间:2018-12-01 23:31:19

标签: python python-3.x pyqt pyqt5 return-value

为了进行一些计算,我需要读取一些信息值,这些信息值由用户在不同的小部件上设置,并且稍后应通过单击按钮将值传递给类。该类激活并计算一些数据,然后将该数据传递给其他小部件以进行绘图或书写。...

在进行分类之前,我们还需要标记何时缺少一个或多个数据。

可视化:

图1:用户单击按钮,然后按钮继续进行并从多个“小部件”选项卡中读取值,并将这些数据传递给类。

enter image description here

图2:通常由用户设置以供进一步阅读的信息。

enter image description here

图3:通常由用户设置以供阅读的信息。

enter image description here

图4:通常由用户设置以供阅读的信息。

![enter image description here

图5:通常由用户设置以供阅读的信息。

enter image description here

完整代码:

import sys
from PyQt5 import QtCore, QtWidgets, QtGui

class Tabwidget(QtWidgets.QWidget):
    def __init__(self, parent=None):
        super( Tabwidget, self).__init__()
        self.setFixedSize(400, 230)      
        tab = QtWidgets.QTabWidget()
        self.geometry = firsttab()
        self.roundsection = self.geometry

        self.A = ClassA()
        self.B = ClassB()
        self.C = ClassC()

        tab.addTab(self.geometry,'A')
        tab.addTab(self.A,'B')
        tab.addTab(self.B,'C')
        tab.addTab(self.C, 'D')
        tab.addTab(LoadTable(), 'E')
        tab.setFont(QtGui.QFont("Georgia",9,QtGui.QFont.Normal))

        vboxlayout = QtWidgets.QVBoxLayout()
        vboxlayout.addWidget(tab)
        self.setLayout(vboxlayout)


class firsttab(QtWidgets.QWidget):
    valueChanged = QtCore.pyqtSignal(int)
    valuesChanged = QtCore.pyqtSignal(int, int)
    def __init__(self, parent=None):
        super(firsttab, self).__init__(parent)

        font = QtGui.QFont("Georgia",8,QtGui.QFont.Normal)

        sectiontypegroupbox = QtWidgets.QGroupBox('&Type',self)
        sectiontypegroupbox.setFont(QtGui.QFont("Georgia",10,QtGui.QFont.Normal))

        tab1button = QtWidgets.QPushButton('')


        circularlabel = QtWidgets.QLabel("Calculate",self)
        circularlabel.setSizePolicy(QtWidgets.QSizePolicy.Expanding,QtWidgets.QSizePolicy.Expanding)
        circularlabel.setFont(font)


        circularlay = QtWidgets.QHBoxLayout()
        circularlay.addWidget(tab1button)
        circularlay.addWidget(circularlabel)


        vboxlayout = QtWidgets.QVBoxLayout()
        vboxlayout.addLayout(circularlay)
        vboxlayout.setSizeConstraint(vboxlayout.SetFixedSize)
        vboxlayout.setContentsMargins(25,25,25,25)

        sectiontypegroupbox.setLayout(vboxlayout)   

        hboxlayout = QtWidgets.QHBoxLayout()
        hboxlayout.addWidget(sectiontypegroupbox)
        self.setLayout(hboxlayout)

#        self.button = Calculate()        
#        tab1button.clicked.connect(self.button.parse_file)



class ClassA(QtWidgets.QWidget):
    def __init__(self, parent=None):
        super(ClassA, self).__init__(parent)
        self.setFont(QtGui.QFont("Helvetica", 10, QtGui.QFont.Normal, italic=False))      

        self.c_lay = QtWidgets.QHBoxLayout()
        fctd = "One\n\nTwo\n\nThree"
        con_strength = QtWidgets.QLabel(fctd)
        self.value = QtWidgets.QLineEdit('Test')
        self.c_lay.addWidget(con_strength)
        self.c_lay.addWidget(self.value, alignment=QtCore.Qt.AlignRight)


        self.combo = QtWidgets.QComboBox()
        self.combo.addItems(["10","12","14","16"])

        self.hbox = QtWidgets.QHBoxLayout()
        self.con = QtWidgets.QLabel("Number: ")
        self.hbox.addWidget(self.con)
        self.hbox.addWidget(self.combo)

        self.vlay = QtWidgets.QVBoxLayout()
        self.vlay.addLayout(self.hbox)
        self.vlay.addLayout(self.c_lay)
        self.vlay.addStretch()

        Concrete_Group = QtWidgets.QGroupBox()
        Concrete_Group.setTitle("&GroupA")
        Concrete_Group.setLayout(self.vlay)

        lay = QtWidgets.QVBoxLayout(self)
        lay.addWidget(Concrete_Group)

        self.comth = ["10","12","14","16"]
        self.combo.activated.connect(self.setdatastrength)

    @QtCore.pyqtSlot(int)
    def setdatastrength(self, index):
        value = self.comth[index]
        self.display_data(value)


    def display_data(self, value):
        try:

            f = value
            f_value = "{}"
            self.value.setText(f_value.format(f))

        except ValueError:
            print("Error")


class ClassB(QtWidgets.QWidget):
    def __init__(self, parent=None):
        super(ClassB, self).__init__(parent)
        self.setFont(QtGui.QFont("Helvetica", 10, QtGui.QFont.Normal, italic=False))


        self.combo_exclass = QtWidgets.QComboBox()
        self.combo_exclass.addItems([" Very dry area"," Dry or permanently wet"," Wet, rarely dry"," Moderate humidity"," Tidal splash & spray zones"])


        self.combo_lclass = QtWidgets.QComboBox()
        self.combo_lclass.addItems(["L2","L4","L6","L8"])

        self.combo_vct = QtWidgets.QComboBox()


        self.combo_vct.addItems(["0.10","0.20","0.30","0.40",
                                        "0.50","0.60","0.70"])

        self.combo_in = QtWidgets.QComboBox()
        self.combo_in.addItems(["Class1","Class2","Class3"])        

        self.tbox = QtWidgets.QHBoxLayout()
        self.exclass = QtWidgets.QLabel("Class1: ")
        self.tbox.addWidget(self.exclass)
        self.tbox.addWidget(self.combo_exclass)


        self.mtbox = QtWidgets.QHBoxLayout()
        self.lclass = QtWidgets.QLabel("Class2: ")

        self.mtbox.addWidget(self.lclass)
        self.mtbox.addWidget(self.combo_lclass)


        self.mbbox = QtWidgets.QHBoxLayout()
        self.vct = QtWidgets.QLabel("Class3: ")
        self.mbbox.addWidget(self.vct)
        self.mbbox.addWidget(self.combo_vct)

        self.bbox = QtWidgets.QHBoxLayout()
        self.inl = QtWidgets.QLabel("Class4: ")
        self.bbox.addWidget(self.inl)
        self.bbox.addWidget(self.combo_in)


        self.grid = QtWidgets.QGridLayout()
        self.grid.addLayout(self.tbox, 0, 0, 1, 2)
        self.grid.addLayout(self.mtbox, 1, 0)
        self.grid.addLayout(self.mbbox, 2, 0)
        self.grid.addLayout(self.bbox, 3, 0)

        Environment_Group = QtWidgets.QGroupBox()
        Environment_Group.setTitle("&Group2")
        Environment_Group.setLayout(self.grid)

        vlay = QtWidgets.QVBoxLayout(self)
        vlay.addWidget(Environment_Group)


class ClassC(QtWidgets.QWidget):
    def __init__(self, parent=None):
        super(ClassC, self).__init__(parent)
        self.setFont(QtGui.QFont("Helvetica", 10, QtGui.QFont.Normal, italic=False))      


        filenameLabel = QtWidgets.QLabel("Name number:")
        fileNameEdit = QtWidgets.QLineEdit()


        ftablayout = QtWidgets.QVBoxLayout()
        ftablayout.addWidget(filenameLabel)
        ftablayout.addWidget(fileNameEdit)
        self.setLayout(ftablayout)

class LoadTable(QtWidgets.QTableWidget):
    def __init__(self, parent=None):
        super(LoadTable, self).__init__(1, 3, parent)
        self.setFont(QtGui.QFont("Helvetica", 10, QtGui.QFont.Normal, italic=False))   
        headertitle = ("A","B","C")
        self.setHorizontalHeaderLabels(headertitle)
        self.verticalHeader().hide()
        self.horizontalHeader().setHighlightSections(False)
        self.horizontalHeader().setSectionResizeMode(QtWidgets.QHeaderView.Fixed)

        self.setSelectionMode(QtWidgets.QAbstractItemView.NoSelection)
        self.setColumnWidth(0, 130)

        combox_lay = QtWidgets.QComboBox(self)
        combox_lay.addItems(["I","II"])
        self.setCellWidget(0, 2, combox_lay)

class Calculate():
    def __init__(self,a,b,c,d,e,f,g):

        self.x_value = None
        self.a_frc = None
        self.b_cap = None
        self.bsst = None
        self.tsst = None
        self.bsst = None
        self.tsstr = None
        self.parse_file(a,b,c,d,e,f,g)

    def parse_file(self,a,b,c,d,e,f,g):
        #all the code for calculation where:
        pass
        self.x_value = '{:.3f}'.format(a)
        self.a_frc = '{:.3f}'.format(b)
        self.b_cap = '{:.3f}'.format(c)
        self.bsst = '{:.3f}'.format(d)
        self.tsst = '{:.3f}'.format(e)
        self.bsst = '{:.3f}'.format(f)
        self.tsstr = '{:.3f}'.format(g)

    def __str__(self):
        return ('\nx value: {0} \nAforce: {1} \nb capacity : {2} \nBottom strain : {3} '
                '\nTop strain : {4} \nBottom stress :{5} \nTop stress : {6}'
                .format(self.x_value, self.a_frc, self.b_cap, self.bsst, self.tsst, self.bsst, self.tsstr))

if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    w = Tabwidget()
    w.show()
    sys.exit(app.exec_())

感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

由于您没有指出要获取的内容,因此我将指出通用方法:您必须具有一种获取数据的方法:

class Some_Widget(FooWidget):
    # ...
    def get_data(self):
         return some_values

在FirstTab的情况下,我不理解您创建的信号,恕我直言,我认为您只需要一个称为clicked的信号,该信号在按钮的单击信号被传输并将其传输到主窗口时发出数据可以访问。

另一方面,删除{:.3f}部分,因为数据不是数字而是字符串(也许您必须将它们转换为字符串,但是由于没有详细信息,仅此而已),所以我只打印它

考虑到上述情况,并假设几件事,因为您没有指出任何具体的内容,因此以下代码是可行的解决方案:

import sys
from PyQt5 import QtCore, QtWidgets, QtGui

class Tabwidget(QtWidgets.QWidget):
    def __init__(self, parent=None):
        super( Tabwidget, self).__init__()
        self.setFixedSize(400, 230)      
        tab = QtWidgets.QTabWidget()
        self.geometry = FirstTab()
        self.geometry.clicked.connect(self.on_clicked)

        self.A = ClassA()
        self.B = ClassB()
        self.C = ClassC()

        self.load_table = LoadTable()

        tab.addTab(self.geometry,'A')
        tab.addTab(self.A,'B')
        tab.addTab(self.B,'C')
        tab.addTab(self.C, 'D')
        tab.addTab(self.load_table, 'E')
        tab.setFont(QtGui.QFont("Georgia",9,QtGui.QFont.Normal))

        vboxlayout = QtWidgets.QVBoxLayout()
        vboxlayout.addWidget(tab)
        self.setLayout(vboxlayout)

        self._calculate = Calculate()

    def on_clicked(self):
        d1 = self.A.get_data()
        d2 = self.B.get_data()
        d3 = self.C.get_data()
        d4 = self.load_table.get_data()
        self._calculate.parse_file(*d1, *d2, *d3, *d4)


class FirstTab(QtWidgets.QWidget):
    clicked = QtCore.pyqtSignal()

    def __init__(self, parent=None):
        super(FirstTab, self).__init__(parent)

        font = QtGui.QFont("Georgia",8,QtGui.QFont.Normal)

        sectiontypegroupbox = QtWidgets.QGroupBox('&Type',self)
        sectiontypegroupbox.setFont(QtGui.QFont("Georgia",10,QtGui.QFont.Normal))

        tab1button = QtWidgets.QPushButton()


        circularlabel = QtWidgets.QLabel("Calculate",self)
        circularlabel.setSizePolicy(QtWidgets.QSizePolicy.Expanding,QtWidgets.QSizePolicy.Expanding)
        circularlabel.setFont(font)


        circularlay = QtWidgets.QHBoxLayout()
        circularlay.addWidget(tab1button)
        circularlay.addWidget(circularlabel)


        vboxlayout = QtWidgets.QVBoxLayout()
        vboxlayout.addLayout(circularlay)
        vboxlayout.setSizeConstraint(vboxlayout.SetFixedSize)
        vboxlayout.setContentsMargins(25,25,25,25)

        sectiontypegroupbox.setLayout(vboxlayout)   

        hboxlayout = QtWidgets.QHBoxLayout(self)
        hboxlayout.addWidget(sectiontypegroupbox)
        tab1button.clicked.connect(self.clicked)


class ClassA(QtWidgets.QWidget):
    def __init__(self, parent=None):
        super(ClassA, self).__init__(parent)
        self.setFont(QtGui.QFont("Helvetica", 10, QtGui.QFont.Normal, italic=False))      

        self.c_lay = QtWidgets.QHBoxLayout()
        fctd = "One\n\nTwo\n\nThree"
        con_strength = QtWidgets.QLabel(fctd)
        self.value = QtWidgets.QLineEdit('Test')
        self.c_lay.addWidget(con_strength)
        self.c_lay.addWidget(self.value, alignment=QtCore.Qt.AlignRight)

        self.combo = QtWidgets.QComboBox()
        self.combo.addItems(["10","12","14","16"])

        self.hbox = QtWidgets.QHBoxLayout()
        self.con = QtWidgets.QLabel("Number: ")
        self.hbox.addWidget(self.con)
        self.hbox.addWidget(self.combo)

        self.vlay = QtWidgets.QVBoxLayout()
        self.vlay.addLayout(self.hbox)
        self.vlay.addLayout(self.c_lay)
        self.vlay.addStretch()

        Concrete_Group = QtWidgets.QGroupBox()
        Concrete_Group.setTitle("&GroupA")
        Concrete_Group.setLayout(self.vlay)

        lay = QtWidgets.QVBoxLayout(self)
        lay.addWidget(Concrete_Group)

        self.combo.activated[str].connect(self.display_data)

    @QtCore.pyqtSlot(str)
    def display_data(self, value):
        try:
            f = value
            f_value = "{}"
            self.value.setText(f_value.format(f))
        except ValueError:
            print("Error")

    def get_data(self):
        return tuple([self.combo.currentText(), self.value.text()])

class ClassB(QtWidgets.QWidget):
    def __init__(self, parent=None):
        super(ClassB, self).__init__(parent)
        self.setFont(QtGui.QFont("Helvetica", 10, QtGui.QFont.Normal, italic=False))


        self.combo_exclass = QtWidgets.QComboBox()
        self.combo_exclass.addItems([" Very dry area"," Dry or permanently wet"," Wet, rarely dry"," Moderate humidity"," Tidal splash & spray zones"])


        self.combo_lclass = QtWidgets.QComboBox()
        self.combo_lclass.addItems(["L2","L4","L6","L8"])

        self.combo_vct = QtWidgets.QComboBox()


        self.combo_vct.addItems(["0.10","0.20","0.30","0.40",
                                        "0.50","0.60","0.70"])

        self.combo_in = QtWidgets.QComboBox()
        self.combo_in.addItems(["Class1","Class2","Class3"])        

        self.tbox = QtWidgets.QHBoxLayout()
        self.exclass = QtWidgets.QLabel("Class1: ")
        self.tbox.addWidget(self.exclass)
        self.tbox.addWidget(self.combo_exclass)


        self.mtbox = QtWidgets.QHBoxLayout()
        self.lclass = QtWidgets.QLabel("Class2: ")

        self.mtbox.addWidget(self.lclass)
        self.mtbox.addWidget(self.combo_lclass)

        self.mbbox = QtWidgets.QHBoxLayout()
        self.vct = QtWidgets.QLabel("Class3: ")
        self.mbbox.addWidget(self.vct)
        self.mbbox.addWidget(self.combo_vct)

        self.bbox = QtWidgets.QHBoxLayout()
        self.inl = QtWidgets.QLabel("Class4: ")
        self.bbox.addWidget(self.inl)
        self.bbox.addWidget(self.combo_in)


        self.grid = QtWidgets.QGridLayout()
        self.grid.addLayout(self.tbox, 0, 0, 1, 2)
        self.grid.addLayout(self.mtbox, 1, 0)
        self.grid.addLayout(self.mbbox, 2, 0)
        self.grid.addLayout(self.bbox, 3, 0)

        Environment_Group = QtWidgets.QGroupBox()
        Environment_Group.setTitle("&Group2")
        Environment_Group.setLayout(self.grid)

        vlay = QtWidgets.QVBoxLayout(self)
        vlay.addWidget(Environment_Group)

    def get_data(self):
        return tuple(combo.currentText() for combo in (self.combo_exclass, self.combo_lclass, self.combo_vct, self.combo_in))


class ClassC(QtWidgets.QWidget):
    def __init__(self, parent=None):
        super(ClassC, self).__init__(parent)
        self.setFont(QtGui.QFont("Helvetica", 10, QtGui.QFont.Normal, italic=False))      

        filenameLabel = QtWidgets.QLabel("Name number:")
        self.fileNameEdit = QtWidgets.QLineEdit()
        ftablayout = QtWidgets.QVBoxLayout(self)
        ftablayout.addWidget(filenameLabel)
        ftablayout.addWidget(self.fileNameEdit)

    def get_data(self):
        return tuple(self.fileNameEdit.text(),)


class LoadTable(QtWidgets.QTableWidget):
    def __init__(self, parent=None):
        super(LoadTable, self).__init__(1, 3, parent)
        self.setFont(QtGui.QFont("Helvetica", 10, QtGui.QFont.Normal, italic=False))   
        headertitle = ("A","B","C")
        self.setHorizontalHeaderLabels(headertitle)
        self.verticalHeader().hide()
        self.horizontalHeader().setHighlightSections(False)
        self.horizontalHeader().setSectionResizeMode(QtWidgets.QHeaderView.Fixed)

        self.setSelectionMode(QtWidgets.QAbstractItemView.NoSelection)
        self.setColumnWidth(0, 130)

        combox_lay = QtWidgets.QComboBox(self)
        combox_lay.addItems(["I","II"])
        self.setCellWidget(0, 2, combox_lay)

    def get_data(self):
        return tuple([self.cellWidget(0, 2).currentText()])

class Calculate():
    def parse_file(self,a,b,c,d,e,f,g):
        print(a, b, c, d, e, f, g)

if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    w = Tabwidget()
    w.show()
    sys.exit(app.exec_())

更新:

# ...
class LoadTable(QtWidgets.QTableWidget):
    # ...
    def get_data(self):
        val1 = self.item(0, 0).text()  if self.item(0, 0) else ""
        val2 = self.item(0, 1).text()  if self.item(0, 1) else ""
        return tuple([val1, val2, self.cellWidget(0, 2).currentText()])

# ...
class Calculate():
    def parse_file(self,a,b,c,d,e,f,g, h, i):
        print(a, b, c, d, e, f, g, h, i)