按下主窗口PyQT的按钮时传递结果

时间:2019-07-14 04:31:01

标签: python pyqt

我正在尝试开发代码以查看图像和这些图像的元数据。按下按钮对图像评分时,它将返回1到5之间的值。

由于@eyllanesc,我遵循了Return value from button click的理解

是否有更有效的方法来解决此问题?我是PYQT的新手,我不想犯任何疯狂的错误。

from PyQt5 import QtWidgets, QtCore
from output_image import Ui_MainWindow #Import generated file
import sys
import pandas as pd
from PyQt5.QtWidgets import QApplication

filename = "data_images.csv"

data = pd.DataFrame(pd.read_csv(filename, dtype = {'Image': str, 'All Images': str}))

class PandasModel(QtCore.QAbstractTableModel): 
    def __init__(self, df = pd.DataFrame(), parent=None): 
        QtCore.QAbstractTableModel.__init__(self, parent=parent)
        self._df = df

    def headerData(self, section, orientation, role=QtCore.Qt.DisplayRole):
        if role != QtCore.Qt.DisplayRole:
            return QtCore.QVariant()

        if orientation == QtCore.Qt.Horizontal:
            try:
                return self._df.columns.tolist()[section]
            except (IndexError, ):
                return QtCore.QVariant()
        elif orientation == QtCore.Qt.Vertical:
            try:
                # return self.df.index.tolist()
                return self._df.index.tolist()[section]
            except (IndexError, ):
                return QtCore.QVariant()

    def data(self, index, role=QtCore.Qt.DisplayRole):
        if role != QtCore.Qt.DisplayRole:
            return QtCore.QVariant()

        if not index.isValid():
            return QtCore.QVariant()

        return QtCore.QVariant(str(self._df.ix[index.row(), index.column()]))

    def setData(self, index, value, role):
        row = self._df.index[index.row()]
        col = self._df.columns[index.column()]
        if hasattr(value, 'toPyObject'):
            # PyQt4 gets a QVariant
            value = value.toPyObject()
        else:
            # PySide gets an unicode
            dtype = self._df[col].dtype
            if dtype != object:
                value = None if value == '' else dtype.type(value)
        self._df.set_value(row, col, value)
        return True

    def rowCount(self, parent=QtCore.QModelIndex()): 
        return len(self._df.index)

    def columnCount(self, parent=QtCore.QModelIndex()): 
        return len(self._df.columns)

    def sort(self, column, order):
        colname = self._df.columns.tolist()[column]
        self.layoutAboutToBeChanged.emit()
        self._df.sort_values(colname, ascending= order == QtCore.Qt.AscendingOrder, inplace=True)
        self._df.reset_index(inplace=True, drop=True)
        self.layoutChanged.emit()


class ApplicationWindow(QtWidgets.QMainWindow, Ui_MainWindow):
    def __init__(self):
        super(ApplicationWindow, self).__init__()
        self.rating = None

        #Create UI
#        self.ui = Ui_MainWindow()
        self.setupUi(self)

        #Exit Button
        self.actionExit.triggered.connect(self.close)

        #Table Creation and Formatting
        model = PandasModel(display)
        self.tableView.setModel(model)
        header = self.tableView.horizontalHeader()       
        header.setSectionResizeMode(0, QtWidgets.QHeaderView.Stretch)

#        self.pushButton_sne.clicked.connect(self.handle_sne)
        self.pushButton_sne.clicked.connect(self.handle_sne)
        self.pushButton_bc.clicked.connect(self.handle_sne)
        self.pushButton_neutral.clicked.connect(self.handle_sne)
        self.pushButton_gc.clicked.connect(self.handle_sne)
        self.pushButton_grc.clicked.connect(self.handle_sne)


    def handle_sne(self):

        if str(self.sender().objectName()) == "pushButton_sne": self.rating = 1
        if str(self.sender().objectName()) == "pushButton_bc": self.rating = 2
        if str(self.sender().objectName()) == "pushButton_neutral": self.rating = 3
        if str(self.sender().objectName()) == "pushButton_gc": self.rating = 4
        if str(self.sender().objectName()) == "pushButton_grc": self.rating = 5

        self.close()

def main():
    if not QtWidgets.QApplication.instance():
        app = QtWidgets.QApplication(sys.argv)
    else:
        app = QtWidgets.QApplication.instance()
    app.aboutToQuit.connect(app.deleteLater)
    application = ApplicationWindow()
    application.show()
#    selection = application
#    QtWidgets.QApplication.setQuitOnLastWindowClosed(True)
#    sys.exit(app.exec_())
    quit(app.exec_())
    return application.rating
#if __name__ == "__main__":
#    main()

for _, row in data.iterrows():
    display = row.to_frame(name='Image Metadata')
    rating = main()
    print("rating:"+str(rating))

0 个答案:

没有答案