S
S
SOmar2016-08-04 09:12:18
Python
SOmar, 2016-08-04 09:12:18

Python adding to combobox?

how to add sheet names to ComboBox and then get them in sheet_by_index[]

import xlrd, csv
import sys
from PyQt4 import QtGui
from PyQt4 import QtCore

class OpenFile(QtGui.QMainWindow):
   def __init__(self, parent=None):
       QtGui.QMainWindow.__init__(self, parent)
       self.setGeometry(300, 300, 325, 100)
       self.setWindowTitle(self.trUtf8('Выбор файла'))
       self.setWindowIcon(QtGui.QIcon('imageformats\icon.jpeg'))

       pButton = QtGui.QPushButton('Открыть файл', self)
       pButton.setGeometry(25, 15, 125, 25)       
       self.connect(pButton, QtCore.SIGNAL('clicked()'), self.showDialog)

       quit = QtGui.QPushButton('Выход', self)
       quit.setGeometry(175, 15, 125, 25)
       self.connect(quit, QtCore.SIGNAL('clicked()'),
                    QtGui.qApp, QtCore.SLOT('quit()'))

       comboBox = QtGui.QComboBox(self)
       comboBox.setGeometry(QtCore.QRect(25, 55, 125, 25))
       comboBox.setObjectName(self.trUtf8("comboBox"))
             
   def showDialog(self):
       filename = QtGui.QFileDialog.getOpenFileName(self, 'Выбор файла', '*xls')
      
       wbr = xlrd.open_workbook(filename,formatting_info=True)

       sheetName = []
       
       for sName in wbr.sheet_names():
          sheetName.append(wbr.sheet_by_name(sName))

       #//////////////////Индекс листа///////////////////////
       #sheet = wbr.sheet_by_index(0)

       vals = []
       i = 0
       a = 0

       for rows in range(sheet.nrows):
          vals.append(sheet.row_values(rows))

       #/////////////Удаляем из массива шапку Промоактивности//////////////
       for a in range(4):
          del vals[0]
          a = +1

       file_csv = open('C:\promo.csv', 'w')

       for i in range(sheet.nrows - 4):
          stroka_0 = str(vals[i]).replace('[','')
          stroka_1 = stroka_0.replace(',',';')
          stroka_2 = stroka_1.replace(']','')
          stroka_3 = stroka_2.replace(' ','')
          stroka_4 = stroka_3.replace("'",'')
          stroka_5 = stroka_4.replace(".0",'')
          file_csv.write(stroka_5 + "\n")
          i=+1

       file_csv.close()       
   
app = QtGui.QApplication(sys.argv)
cd = OpenFile()
cd.show()
sys.exit(app.exec())

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sergey6661313, 2016-08-05
@SOmar

blah blah blah create comboBox as a variable of the created OpenFile object:

class OpenFile(QtGui.QMainWindow):
    def __init__(self, parent=None):
      ...   ...   ...
      self.comboBox = QtGui.QComboBox(self)
      self.comboBox.setGeometry(QtCore.QRect(25, 55, 125, 25))
      self.comboBox.setObjectName(self.trUtf8("comboBox"))

then in the showDialog method you can refer to self. combo box:
for sName in wbr.sheet_names():
        sheetName.append(wbr.sheet_by_name(sName))
        self.comboBox.addItem(str(sName))

blah blah blah you can find out its index using the currentIndex() method
blah blah blah separate method blah blah blah.
____________________________________________________________________________________________
addition to the answer: to
summarize: we have already replaced all comboBoxes with self.comboBox (you did that, right?)
removed to the (unfriendly word) sheetName and its filling cycle. (why do you need it if you have an excellent comboBox?)
we also have to make wbr itself a "long-playing" variable (we will use it in our "separate" method, so losing it will be a disaster. )
i.e. we finished the def showDialog method (self):
to next 3 lines:
filename = QtGui.QFileDialog.getOpenFileName(self, 'Select File', '*xls')
self.wbr = xlrd.open_workbook(filename,
self.comboBox.addItems(self.wbr.sheet_names())
What to do with all this code below?
well, you can make another button "write_to_csv" and a slot method for your code.
an example for linking a button and a method is already in your example. you just need to write def insert_court_any_name (self) before your code: and duplicate the button, just specify a different name and other coordinates, and where connect change everything accordingly. And just click on the button after you select the sheet.
class OpenFile(QtGui.QMainWindow):
    def __init__(self, parent=None):
        QtGui.QMainWindow.__init__(self, parent)
        ...  ...  ...

        pButton2 = QtGui.QPushButton('записать в csv', self)
        pButton2.setGeometry(175, 55, 125, 25)
        self.connect(pButton2, QtCore.SIGNAL('clicked()'), self.slot_list_selected)

    def showDialog(self):
        filename = QtGui.QFileDialog.getOpenFileName(self, 'Выбор файла', '*xls')
        self.wbr = xlrd.open_workbook(filename, formatting_info=True)
        self.comboBox.addItems(self.wbr.sheet_names())

    def slot_list_selected(self):
        # //////////////////Индекс листа///////////////////////
        sheet = self.wbr.sheet_by_index(self.comboBox.currentIndex())

        ... ... ...

But we're not looking for easy ways, are we?
+ we want to get to know QT better.
our true version without the participation of an additional button:
I called the method slot_list_selected. and we'll connect it directly to the combobox's change signal like this:
self.comboBox.currentIndexChanged.connect(self.slot_list_selected) is an alternative, shorter method of connecting signals and slots (than self.connect(self.comboBox, QtCore.SIGNAL(' currentIndexChanged(int)'), self.slot_list_selected) )
but there is a trick - the signal not only calls the method but also passes it an int (the selected index). So our slot method must accept it.
def slot_list_selected(self, list_index ):
well, since it is still transmitted to us, we could immediately use it.
instead of sheet = self.wbr.sheet_by_index(self.comboBox.currentIndex())
sheet = self.wbr.sheet_by_index(list_index)
in principle further your magic code seems to work fine. but it will be called at the moment when we fill our comboBox (initially an empty combo shows "-1", and when we fill its value becomes "0" which causes the currentIndexChanged signal)
this is solved by turning off the signals with the command self.comboBox.blockSignals(True)
But also pitfalls will come out here: in particular, the first element (with index 0) will be selected by default and when trying to select it, the index will not change.
Here are 2 options again:
1) make the first item not the name of the sheet, but your own. (if it is also called "select sheet", then this will serve as an additional hint for the user.)
rewrite self.comboBox.addItems(self.wbr.sheet_names()) to
self.comboBox.addItems(["select sheet"] +
self.wbr.sheet_names ()) indexes have shifted and sheet is calculated with index -1:
sheet = self.wbr.sheet_by_index(list_index-1)
and you will have to check that list_index is greater than zero. (we don't want to read sheet number "-1")
if list_index:
your code.
having played enough with your program, we notice that the comboBox is filled when a file is selected, but it does not erase the previous values.
fix adding before additems
self.comboBox.clear()
seems to be fine.
2) an easier way:
just use the activated signal instead of currentIndexChanged, then it will react even to the selection of an already selected one. But I still recommend doing the operations from the first method.
Total code:
class OpenFile(QtGui.QMainWindow):
    def __init__(self, parent=None):
        QtGui.QMainWindow.__init__(self, parent)
        self.setGeometry(300, 300, 325, 100)
        self.setWindowTitle(self.trUtf8('Выбор файла'))
        self.setWindowIcon(QtGui.QIcon('imageformats\icon.jpeg'))

        pButton = QtGui.QPushButton('Открыть файл', self)
        pButton.setGeometry(25, 15, 125, 25)
        self.connect(pButton, QtCore.SIGNAL('clicked()'), self.showDialog)

        quit = QtGui.QPushButton('Выход', self)
        quit.setGeometry(175, 15, 125, 25)
        self.connect(quit, QtCore.SIGNAL('clicked()'),
                     QtGui.qApp, QtCore.SLOT('quit()'))

        self.comboBox = QtGui.QComboBox(self)
        self.comboBox.setGeometry(QtCore.QRect(25, 55, 125, 25))
        self.comboBox.setObjectName(self.trUtf8("comboBox"))
        self.comboBox.activated.connect(self.slot_list_selected)

    def showDialog(self):
        filename = QtGui.QFileDialog.getOpenFileName(self, 'Выбор файла', '*xls')
        self.wbr = xlrd.open_workbook(filename, formatting_info=True)
        self.comboBox.blockSignals(True)
        self.comboBox.clear()
        self.comboBox.addItems(["выберите лист"] + self.wbr.sheet_names())
        self.comboBox.blockSignals(False)


    def slot_list_selected(self, list_index):
        if list_index:
            # //////////////////Индекс листа///////////////////////
            sheet = self.wbr.sheet_by_index(list_index-1)
            print(list_index)
    
            vals = []
            i = 0
            a = 0
    
            for rows in range(sheet.nrows):
                vals.append(sheet.row_values(rows))
    
            # /////////////Удаляем из массива шапку Промоактивности//////////////
            for a in range(4):
                del vals[0]
                a = +1
    
            file_csv = open('C:\promo.csv', 'w')
    
            for i in range(sheet.nrows - 4):
                stroka_0 = str(vals[i]).replace('[', '')
                stroka_1 = stroka_0.replace(',', ';')
                stroka_2 = stroka_1.replace(']', '')
                stroka_3 = stroka_2.replace(' ', '')
                stroka_4 = stroka_3.replace("'", '')
                stroka_5 = stroka_4.replace(".0", '')
                file_csv.write(stroka_5 + "\n")
                i = +1
    
            file_csv.close()

S
SOmar, 2016-08-06
@SOmar

I choose a book first. In ComboBox I load sheets from the book. I select a sheet and write the data from it into a csv file! You can ask a question if it’s not difficult for you to describe as beautifully as “That is, all the code below most likely needs to be done as a separate method” how to do it!

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question