2017-01-20 11 views
0

QTableWidget을 사용하여 CSV 데이터를 표시하고 있습니다. 키워드를 입력 할 때 Excel 작업과 비슷한 방식으로 필터 작업을 수행하려고합니다. 모든 행과 열에 영향을 주어야합니다.QTableWidget에서 필터 옵션을 사용하는 방법

from PyQt4 import QtCore, QtGui, uic 
from PyQt4.QtCore import QString 

from PyQt4.QtGui import * 
from PyQt4.QtCore import * 

import MySQLdb 
import os 
import time 
import sys 
import hashlib 
import getpass 
import webbrowser 
import csv 

filter_class = uic.loadUiType("filter.ui")[0] 

class Filter_window(QtGui.QWidget, filter_class): 
    def __init__(self, parent=None, *args, **kwargs): 
     QtGui.QMainWindow.__init__(self, parent) 
     self.setupUi(self) 

     #self.selectall.clicked.connect(self.selectall_application) 
     #self.filnext.clicked.connect(self.filnext_application) 

     self.loadAll() 


    def loadAll(self): 

     with open("Rts.csv", "rb") as inpfil: 

      reader = csv.reader(inpfil, delimiter = ',') 
      csheader = reader.next() 
      ncol = len(csheader) 
      data = list(reader) 
      row_count = len(data) 

      self.filterall.setRowCount(row_count) 
      self.filterall.setColumnCount(ncol) 
      self.filterall.setHorizontalHeaderLabels(QString('%s' % ', '.join(map(str, csheader))).split(",")) 

      for ii in range(0, row_count): 
       print data[ii] 

       mainins = data[ii] 
       print mainins 


       for var in range(0,ncol):             
        print mainins[var], "\n" 
        self.filterall.setItem(ii, var, QTableWidgetItem(mainins[var])) 


if __name__ == '__main__': 
    app = QtGui.QApplication(sys.argv) 
    filterwin = Filter_window() 
    filterwin.show() 
    sys.exit(app.exec_()) 

filterall는 QTableWidget FOT 오브젝트 이름

.ui 번호 :

이것은 각 항목의 헤더를 클릭하여 여과
<?xml version="1.0" encoding="UTF-8"?> 
<ui version="4.0"> 
<class>allCases</class> 
<widget class="QWidget" name="allCases"> 
    <property name="geometry"> 
    <rect> 
    <x>0</x> 
    <y>0</y> 
    <width>597</width> 
    <height>466</height> 
    </rect> 
    </property> 
    <property name="windowTitle"> 
    <string>All Cases</string> 
    </property> 
    <layout class="QGridLayout" name="gridLayout"> 
    <item row="3" column="0" colspan="4"> 
    <widget class="Line" name="line"> 
    <property name="orientation"> 
     <enum>Qt::Horizontal</enum> 
    </property> 
    </widget> 
    </item> 
    <item row="4" column="3"> 
    <widget class="QPushButton" name="filnext"> 
    <property name="font"> 
     <font> 
     <pointsize>12</pointsize> 
     </font> 
    </property> 
    <property name="text"> 
     <string>Next</string> 
    </property> 
    </widget> 
    </item> 
    <item row="4" column="2"> 
    <widget class="QPushButton" name="selectall"> 
    <property name="font"> 
     <font> 
     <pointsize>12</pointsize> 
     </font> 
    </property> 
    <property name="text"> 
     <string>Select All</string> 
    </property> 
    </widget> 
    </item> 
    <item row="0" column="1"> 
    <widget class="QLineEdit" name="filterEdit"> 
    <property name="toolTip"> 
     <string/> 
    </property> 
    <property name="statusTip"> 
     <string/> 
    </property> 
    <property name="placeholderText"> 
     <string>Enter keyword to search</string> 
    </property> 
    </widget> 
    </item> 
    <item row="0" column="2"> 
    <spacer name="horizontalSpacer"> 
    <property name="orientation"> 
     <enum>Qt::Horizontal</enum> 
    </property> 
    <property name="sizeHint" stdset="0"> 
     <size> 
     <width>40</width> 
     <height>20</height> 
     </size> 
    </property> 
    </spacer> 
    </item> 
    <item row="1" column="0" colspan="4"> 
    <widget class="QTableWidget" name="filterall"/> 
    </item> 
    </layout> 
</widget> 
<resources/> 
<connections/> 
</ui> 
+0

당신은 또한 우리에게 filter.ui의 내용을 표시 할 수? – eyllanesc

+0

어떻게 필터를 작동 하시겠습니까? – eyllanesc

+0

@eyllanesc 필터를 적용하면 모든 행에 영향을 주어야합니다. 엑셀과 같은 것. 12 개의 열이 있다고 가정 해 봅시다. 헤더를 클릭하면 가능한 모든 텍스트가 표시되어야하며 선택 후에는 해당 텍스트 만 표시해야합니다. 또한 검색 표시 줄에 누군가가 뭔가를 입력하면 3,4,5,6 열을 검색해야합니다. –

답변

0

그것이 가능한 값을 표시하고,이를 확인한다 필터링됩니다.

전체 코드 :

import csv 
import sys 
from PyQt4 import QtCore 

from PyQt4 import QtGui 


class Widget(QtGui.QWidget): 
    def __init__(self, parent=None): 
     super(Widget, self).__init__(parent=parent) 
     self.verticalLayout = QtGui.QVBoxLayout(self) 
     self.filterall = QtGui.QTableWidget(self) 
     self.filterall.setColumnCount(0) 
     self.filterall.setRowCount(0) 
     self.verticalLayout.addWidget(self.filterall) 

     self.loadAll() 
     self.horizontalHeader = self.filterall.horizontalHeader() 
     self.horizontalHeader.sectionClicked.connect(self.on_view_horizontalHeader_sectionClicked) 
     self.keywords = dict([(i, []) for i in range(self.filterall.columnCount())]) 
     self.checkBoxs = [] 
     self.col = None 

    def slotSelect(self, state): 

     for checkbox in self.checkBoxs: 
      checkbox.setChecked(QtCore.Qt.Checked == state) 

    def on_view_horizontalHeader_sectionClicked(self, index): 
     # self.clearFilter() 
     self.menu = QtGui.QMenu(self) 
     self.col = index 

     data_unique = [] 

     self.checkBoxs = [] 

     checkBox = QtGui.QCheckBox("Select all", self.menu) 
     checkableAction = QtGui.QWidgetAction(self.menu) 
     checkableAction.setDefaultWidget(checkBox) 
     self.menu.addAction(checkableAction) 
     checkBox.setChecked(True) 
     checkBox.stateChanged.connect(self.slotSelect) 

     for i in range(self.filterall.rowCount()): 
      if not self.filterall.isRowHidden(i): 
       item = self.filterall.item(i, index) 
       if item.text() not in data_unique: 
        data_unique.append(item.text()) 
        checkBox = QtGui.QCheckBox(item.text(), self.menu) 
        checkBox.setChecked(True) 
        checkableAction = QtGui.QWidgetAction(self.menu) 
        checkableAction.setDefaultWidget(checkBox) 
        self.menu.addAction(checkableAction) 
        self.checkBoxs.append(checkBox) 

     btn = QtGui.QDialogButtonBox(QtGui.QDialogButtonBox.Ok | QtGui.QDialogButtonBox.Cancel, 
            QtCore.Qt.Horizontal, self.menu) 
     btn.accepted.connect(self.menuClose) 
     btn.rejected.connect(self.menu.close) 
     checkableAction = QtGui.QWidgetAction(self.menu) 
     checkableAction.setDefaultWidget(btn) 
     self.menu.addAction(checkableAction) 

     headerPos = self.filterall.mapToGlobal(self.horizontalHeader.pos()) 

     posY = headerPos.y() + self.horizontalHeader.height() 
     posX = headerPos.x() + self.horizontalHeader.sectionPosition(index) 
     self.menu.exec_(QtCore.QPoint(posX, posY)) 

    def menuClose(self): 
     self.keywords[self.col] = [] 
     for element in self.checkBoxs: 
      if element.isChecked(): 
       self.keywords[self.col].append(element.text()) 
     self.filterdata() 
     self.menu.close() 

    def loadAll(self): 
     with open("Rts.csv", "rb") as inpfil: 
      reader = csv.reader(inpfil, delimiter=',') 
      csheader = reader.next() 
      ncol = len(csheader) 
      data = list(reader) 
      row_count = len(data) 

      self.filterall.setRowCount(row_count) 
      self.filterall.setColumnCount(ncol) 
      self.filterall.setHorizontalHeaderLabels(QtCore.QString('%s' % ', '.join(map(str, csheader))).split(",")) 

      for ii in range(0, row_count): 
       mainins = data[ii] 
       for var in range(0, ncol): 
        self.filterall.setItem(ii, var, QtGui.QTableWidgetItem(mainins[var])) 

    def clearFilter(self): 
     for i in range(self.filterall.rowCount()): 
      self.filterall.setRowHidden(i, False) 

    def filterdata(self): 

     columnsShow = dict([(i, True) for i in range(self.filterall.rowCount())]) 

     for i in range(self.filterall.rowCount()): 
      for j in range(self.filterall.columnCount()): 
       item = self.filterall.item(i, j) 
       if self.keywords[j]: 
        if item.text() not in self.keywords[j]: 
         columnsShow[i] = False 
     for key, value in columnsShow.iteritems(): 
      self.filterall.setRowHidden(key, not value) 

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

enter image description here

+0

고맙습니다. 너무 많이 ... 예상대로 멋지고 훌륭하게 작동합니다. 그러나 문제가 있습니다. 이미 QtDesigner에서 만든 GUI가 있습니다. 이 클래스를 추가하면 문제가 발생합니까? –

+0

@PradyumnaCheerala 몇 시간 후에 내가 보여준 코드와 프로젝트로 github에 프로젝트를 업로드합니다. – eyllanesc

+0

@PradyumnaCheerala 전체 코드 : https://github.com/eyllanesc/stackoverflow/tree/master/FilterTable – eyllanesc