当我使用“ currentIndex()”时

时间:2018-12-10 19:35:50

标签: python pyqt5

由于这个问题,我被困在几个小时的学校作业中。我需要检查ListWidget中当前所选项目的索引号(AS INTEGER)。

import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QMessageBox, QListView
from PyQt5.QtGui import QPixmap
import Ui_countries

class MyForm(QMainWindow, Ui_countries.Ui_mainWindow):
    # DON'T TOUCH!
    def __init__(self, parent=None):
        super(MyForm, self).__init__(parent)
        self.setupUi(self)
    # END DON'T TOUCH

        # EVENT HOOKS HERE
        self.countryList.itemClicked.connect(self.CountrySelected)
        self.actionLoad_Countries.triggered.connect(self.LoadCountries)
        self.sqUnits.currentIndexChanged.connect(self.SqUnits)
        #self.updatePopulation.itemClicked.connect(self.updateMemory)

    # RESPONSES HERE    


   # def updateMemory(self):



    def LoadCountries(self):
        global namelist
        global populationlist
        global arealist
        namelist = []
        populationlist = []
        arealist = []

        objFile = open("GUI/countries.txt")

        for line in objFile:
            line = line.replace("\n","")
            lineList = line.split(",")
            self.countryList.addItem(lineList[0])  
            namelist.append(lineList[0])
            populationlist.append(lineList[1])
            arealist.append(lineList[2])
        objFile.close()

    def CountrySelected(self,selectedCountryIndex):

        QMessageBox.information(self,"Country changed!",selectedCountryIndex.text())
        strCountryName = selectedCountryIndex.text()
        strCountryName = strCountryName.replace(" ", "_")
        imagePixmap = QPixmap(f"GUI/Flags/{strCountryName}")
        strCountryName = strCountryName.replace("_", " ")
        self.lblCountryName.setText(strCountryName)
        self.flag.setPixmap(imagePixmap)
        self.flag.resize(imagePixmap.width(),imagePixmap.height())
        idx = self.countryList.currentIndex()
        # self.populationbox.setText(populationlist[idx])
        # selectedCountryIndex.index()
        #^^^^^^^^^^^ useful code

        print(int(strCountryName))

    def SqUnits(self):
        QMessageBox.information(self,"Event Received","Please convert between different units.")
        if self.sqUnits.currentText() == "Sq. Miles":
            self.totalareabox.setText("YAAAAA")
        else:
            self.totalareabox.setText("YEEEE")

# DON'T TOUCH
if __name__ == "__main__":
    app = QApplication(sys.argv)
    the_form = MyForm()
    the_form.show()
    sys.exit(app.exec_())

要关注的区域将是CountrySelected函数。每当我尝试运行idx = self.countryList.currentIndex()而不是整数时,如果我尝试打印idx,都会得到'PyQt5.QtCore.QModelIndex object at 0x051A6470'。我的老师希望我们使用pyqt,但我没有使用它的经验,所以我有点害怕!

1 个答案:

答案 0 :(得分:0)

弄清楚了,同学给我发了这个:index = self.listWidget.currentRow()
不知道为什么索引不起作用,但是,tis,这是在作业到期前一小时进行的性质。