2016-11-23 8 views
1

QAction에서 클립 보드의 구조화 된 텍스트를 QTableWidget에 붙여 넣으려고합니다. 이것은 내 현재 코드입니다 :QTableWidget에서 빈 셀을 편집 할 수 있는지 확인하는 방법은 무엇입니까?

나는 세포가 데이터를 붙여 넣기 전에 편집하고,이를 위해 내가 QTableWidget.item(row, col)를 사용하여 항목을 가져온 다음 내가 항목의 플래그를 확인하는 경우 테스트 할
class PasteCellsAction(qt.QAction): 
    def __init__(self, table): 
     if not isinstance(table, qt.QTableWidget): 
      raise ValueError('CopySelectedCellsAction must be initialised ' + 
          'with a QTableWidget.') 
     super(PasteCellsAction, self).__init__(table) 
     self.table = table 
     self.setText("Paste") 
     self.setShortcut(qt.QKeySequence('Ctrl+V')) 
     self.triggered.connect(self.pasteCellFromClipboard) 

    def pasteCellFromClipboard(self): 
     """Paste text from cipboard into the table. 

     If the text contains tabulations and 
     newlines, they are interpreted as column and row separators. 
     In such a case, the text is split into multiple texts to be paste 
     into multiple cells. 

     :return: *True* in case of success, *False* if pasting data failed. 
     """ 
     selected_idx = self.table.selectedIndexes() 
     if len(selected_idx) != 1: 
      msgBox = qt.QMessageBox(parent=self.table) 
      msgBox.setText("A single cell must be selected to paste data") 
      msgBox.exec_() 
      return False 

     selected_row = selected_idx[0].row() 
     selected_col = selected_idx[0].column() 

     qapp = qt.QApplication.instance() 
     clipboard_text = qapp.clipboard().text() 
     table_data = _parseTextAsTable(clipboard_text) 

     protected_cells = 0 
     out_of_range_cells = 0 

     # paste table data into cells, using selected cell as origin 
     for row in range(len(table_data)): 
      for col in range(len(table_data[row])): 
       if selected_row + row >= self.table.rowCount() or\ 
        selected_col + col >= self.table.columnCount(): 
        out_of_range_cells += 1 
        continue 
       item = self.table.item(selected_row + row, 
             selected_col + col) 
       # ignore empty strings 
       if table_data[row][col] != "": 
        if not item.flags() & qt.Qt.ItemIsEditable: 
         protected_cells += 1 
         continue 
        item.setText(table_data[row][col]) 

     if protected_cells or out_of_range_cells: 
      msgBox = qt.QMessageBox(parent=self.table) 
      msg = "Some data could not be inserted, " 
      msg += "due to out-of-range or write-protected cells." 
      msgBox.setText(msg) 
      msgBox.exec_() 
      return False 
     return True 

.

내 문제는 .item 메서드가 빈 셀에 대해 None을 반환하므로 빈 셀의 플래그를 검사 할 수 없다는 것입니다. 내 코드는 현재 붙여 넣기 영역에 빈 셀이없는 경우에만 작동합니다.

오류 라인 46 (None 반환) 및 50 (AttributeError: 'NoneType' object has no attribute 'flags')에 : 셀이 항목의 플래그를 확인 이외의 편집 가능한 경우 찾는 또 다른 방법은

  item = self.table.item(selected_row + row, 
            selected_col + col) 
      # ignore empty strings 
      if table_data[row][col] != "": 
       if not item.flags() & qt.Qt.ItemIsEditable: 
        ... 

있습니까?

+0

셀이 비어 있기 때문에 '없음'을 반환하지 않지만 셀이 존재하지 않기 때문에 – Chr

+0

나는 이것을 잘 모릅니다. 내 테이블 위젯에서 빈 셀을 시각적으로 볼 수 있습니다. 셀에 데이터 또는 플래그가 설정되어 있지 않으면 항목으로 존재하지 않는다는 것을 의미합니까? – PiRK

+0

그리고 대답이 '예'인 경우 셀의 존재하지 않음이 편집 가능합니까? 아니면 내 위젯 사용자가 항목을 만들지 않고도 쓰기 금지 기능을 사용할 수 있습니까? – PiRK

답변

0

작동하는 것처럼 보이는 해결책을 찾았습니다. item() 메서드가 None을 반환하면 새 항목을 만들어 테이블에 추가합니다.

필자는 쓰기 금지 된 셀의 플래그를 수정할 위험이 있는지에 대해 여전히 의문의 여지가 있습니다. 나는 현재 단지 셀이 쓰기 금지되어 있다고 가정합니다. 이는 반드시 필연적으로 이미 항목이 있음을 의미합니다.

  item = self.table.item(target_row, 
            target_col) 
      # item may not exist for empty cells 
      if item is None: 
       item = qt.QTableWidgetItem() 
       self.table.setItem(target_row, 
            target_col, 
            item) 
      # ignore empty strings 
      if table_data[row_offset][col_offset] != "": 
       if not item.flags() & qt.Qt.ItemIsEditable: 
        protected_cells += 1 
        continue 
       item.setText(table_data[row_offset][col_offset]) 

EDIT : target_row = selected_row + row_offset ... 명시하는 항목이 추가없이 지정된 QTableWidget 캔의

3

치수. 이 경우 셀은 완전히 비어 있습니다. 즉 데이터와 항목이 모두 None이됩니다. 사용자가 셀을 편집하면 데이터가 테이블의 모델에 추가되고 항목이 추가됩니다. 입력 된 값이 빈 문자열 인 경우에도이 작업이 수행됩니다. 기본적으로 모든 셀은 읽기 전용으로 만들기 위해 명시 적으로 조치하지 않는 한 편집 가능합니다.

셀을 읽기 전용으로 만드는 방법은 여러 가지가 있습니다 (예 : setting the edit triggers). 또는 테이블의 edit 메서드를 재정의하십시오. 그러나 메서드 만 개별 테이블 위젯 항목에 플래그를 명시 적으로 설정하는 경우 항목이없는 셀은 편집 가능 및 비어 있다고 가정 할 수 있습니다. (예 : setItem을 사용하지 않고 테이블의 모델을 통해 데이터를 직접 설정하는 경우 셀에는 자동으로 항목이 있음).

+0

QTableView 및 QTableWidget을 사용하여 작업을 수행하기 위해 위젯 대신 모델을 통해 데이터를 가져 오거나 설정하도록 전환했습니다. 이렇게하면 항목을 사용할 필요가 없습니다. – PiRK

관련 문제