2016-12-16 84 views
0

我寫了一個可執行的例子 - 你可以測試它。當您啓動這個程序,你會得到三個QPushButton() -objects和一個QLineEdit的() -object。在那裏你可以安裝或卸載/卸載事件過濾器或關閉應用程序。請安裝事件過濾器並鍵入文本。你會看到我想要的。我想要示例程序來保護空間鍵。在當前版本中,用戶不能按空格鍵超過2次。這個程序確實有效。PyQt 4.我不能刪除QLineEdit()的內容 - 對象

我有一個小問題。當我在QLineEdit() -object中寫入文本,然後突出顯示文本並按下刪除或返回鍵時,什麼都不會發生。我無法刪除文字。我也無法複製標記的文本。

下面的代碼有什麼問題?

#!/usr/bin/env python 
import sys 

from PyQt4.QtCore import QEvent, Qt 
from PyQt4.QtGui import QMainWindow, QWidget, QApplication, QVBoxLayout, QLineEdit, QPushButton 

class Window(QMainWindow): 

    def __init__(self, parent=None): 

     QMainWindow.__init__(self, parent) 

     self.count_space_pressed = 0 
     self.current_pos = None 

     self.init_ui() 
     self.init_signal_slot_push_button() 

    def init_ui(self): 
     centralwidget = QWidget(self) 
     self.input_line_edit = QLineEdit(self) 


     self.close_push = QPushButton(self) 
     self.close_push.setEnabled(False) 
     self.close_push.setText("Close") 

     self.push_install = QPushButton(self) 
     self.push_install.setText("Install eventFilter") 

     self.push_deinstall = QPushButton(self) 
     self.push_deinstall.setText("Deinstall eventFilter") 

     layout = QVBoxLayout(centralwidget)   
     layout.addWidget(self.input_line_edit) 
     layout.addWidget(self.push_install) 
     layout.addWidget(self.push_deinstall) 
     layout.addWidget(self.close_push) 

     self.setCentralWidget(centralwidget) 
     return 

    def install_filter_event(self, widget_object): 
     widget_object.installEventFilter(self) 
     return 

    def deinstall_filter_event(self, widget_object): 
     widget_object.removeEventFilter(self) 
     return 

    def init_signal_slot_push_button(self): 

     self.close_push.clicked.connect(self.close) 
     self.push_install.clicked.connect(lambda: self.install_filter_event(self.input_line_edit)) 
     self.push_deinstall.clicked.connect(lambda: self.deinstall_filter_event(self.input_line_edit)) 
     return 

    def strip_string(self, content, site=None): 
     if site == "right": 
      return content.rstrip() 
     elif site == "right_left": 
      return content.strip() 
     elif site == "left": 
      return content.lstrip() 

    def eventFilter(self, received_object, event): 

     content_line_edit = unicode(received_object.text()) 

     if event.type() == QEvent.KeyPress: 

      if event.key() == Qt.Key_Space: 
       ''' 
        Yes, the user did press the Space-Key. We 
        count how often he pressed the space key. 
       ''' 
       self.count_space_pressed = self.count_space_pressed + 1 

       if int(self.count_space_pressed) > 1: 
        ''' 
         The user did press the space key more than 1 time. 
        ''' 

        self.close_push.setEnabled(False) 

        ''' 
         Now we know the user did press the 
         space key more than 1 time. We take a look, 
         if variablenamed (sel.current_pos) is None. 
         That means, no current position is saved. 
        ''' 
        if self.current_pos is None: 
         ''' 
          Well no current position is saved, 
          that why we save the new position anf 
          then we set the position of the cursor. 
         ''' 

         self.current_pos = received_object.cursorPosition() 

         received_object.setCursorPosition(int(self.current_pos)) 

         received_object.clear() 
         received_object.setText(self.strip_string(content_line_edit, site="right")) 

        else: 
         ''' 
          Well the user press the space key again, for 
          example 3, 4, 5, 6 times we want to keep the 
          old position of the cursor until he press 
          no space key. 
         '''       
         received_object.setCursorPosition(int(self.current_pos)) 

         ''' 
          We have to remove all spaces in a string 
          on the right side and set the content on QLineEdit-widget. 
         ''' 
         received_object.clear() 
         received_object.setText(self.strip_string(content_line_edit, site="right")) 

       else: pass     

      else: 
       ''' 
        No the user didn't press the space key. 
        So we set all setting on default. 
       ''' 
       self.close_push.setEnabled(True) 
       self.current_pos = None 
       self.count_space_pressed = 0 

       received_object.clear() 
       received_object.setText(self.strip_string(content_line_edit, site="left")) 

     # Call Base Class Method to Continue Normal Event Processing 
     return QMainWindow.eventFilter(self, received_object, event) 

if __name__ == '__main__': 
    app = QApplication(sys.argv) 
    window = Window() 
    window.show() 
    app.exec_() 

編輯:

import sys, re 
from PyQt4 import QtCore, QtGui 

class Window(QtGui.QWidget): 
    def __init__(self): 
     super(Window, self).__init__() 
     self.edit = QtGui.QLineEdit(self) 

     self.edit.textChanged.connect(self.handleTextChanged) 
     layout = QtGui.QVBoxLayout(self) 
     layout.addWidget(self.edit) 

     # First we save the the regular expression pattern 
     # in a variable named regex. 
     #@ This means: one whitespace character, followed by 
     #@ one or more whitespaces chatacters 

     regex = r"\s\s+" 

     # Now we comple the pattern. 
     # After then we save the compiled patter 
     # as result in a variable named compiled_re. 
     self.compiled_re = re.compile(regex) 

    def handleTextChanged(self, text): 
     # When the text of a widget-object is changed, 
     # we do something. 

     # Here I am really not sure. 
     # Do you want to look if the given text isn't empty? 
     #@ No, we want to search the string to see if it 
     #@ contains any runs of multiple spaces 

     if self.compiled_re.search(text): 

      # We know that given text is a QString-object. 
      # So we have to convert the given text 
      # into a python-string, because we want to work 
      # with them in python. 
      text = unicode(text) 

      # NOTICE: Do replacements before and after cursor pos 

      # We save the current and correct cursor position 
      # of a QLineEdit()-object in the variable named pos. 
      pos = self.edit.cursorPosition() 

      # Search and Replace: Here the sub()-method 
      # replaces all occurrences of the RE pattern 
      # in string with text. 
      # And then it returns modified string and saves 
      # it in the variables prefix and suffix. 

      # BUT I am not sure If I understand this: [:pos] 
      # and [pos:]. I will try to understnand. 
      # I think we are talking about slicing, right? 
      # And I think the slicing works like string[start:end]: 

      # So text[:pos] means, search and replace all whitesapce 
      # at the end of the text-string. And the same again, but 
      # text[pos:] means, search and replace all whitesapce 
      # at the start of the string-text. 
      #@ Right, but the wrong way round. text[:pos] means from 
      #@ the start of the string up to pos (the prefix); and 
      #@ text[pos:] means from pos up to the end of the string 
      #@ (the suffix) 

      prefix = self.compiled_re.sub(' ', text[:pos]) 
      suffix = self.compiled_re.sub(' ', text[pos:])  

      # NOTICE: Cursor might be between spaces 
      # Now we take a look if the variable prefix ends 
      # with a whitespace and we check if suffix starts 
      # with a whitespace. 

      # BUT, why we do that? 
      #@ Imagine that the string is "A |B C" (with the cursor 
      #@ shown as "|"). If "B" is deleted, we will get "A | C" 
      #@ with the cursor left between multiple spaces. But 
      #@ when the string is split into prefix and suffix, 
      #@ each part will contain only *one* space, so the 
      #@ regexp won't replace them. 

      if prefix.endswith(' ') and suffix.startswith(' '): 

       # Yes its True, so we overwrite the variable named 
       # suffix and slice it. suffix[1:] means, we starts 
       # at 1 until open end. 
       #@ This removes the extra space at the start of the 
       #@ suffix that was missed by the regexp (see above) 

       suffix = suffix[1:] 

      # Now we have to set the text of the QLineEdit()-object, 
      # so we put the both varialbes named prefix and suffix 
      # together. 
      self.edit.setText(prefix + suffix) 

      # After then, we have to set the cursor position. 
      # I know that the len()-method returns the length of the 
      # variable named prefix. 

      # BUT why we have to do that? 
      #@ When the text is set, it will clear the cursor. The 
      #@ prefix and suffix gives the text before and after the 
      #@ old cursor position. Removing spaces may have shifted 
      #@ the old position, so the new postion is calculated 
      #@ from the length of the current prefix 

      self.edit.setCursorPosition(len(prefix)) 

if __name__ == '__main__': 

    app = QtGui.QApplication(sys.argv) 
    window = Window() 
    window.setGeometry(500, 150, 300, 100) 
    window.show() 
    sys.exit(app.exec_()) 

編輯2:

兩個問題:

第一個問題:在if.condition,我們一起來看看如果前綴結尾和後綴以sapces開頭,那麼我們就是a回合在後綴的開頭刪除額外的空間。但是爲什麼我們不在前綴的開始處刪除多餘的空間? 想象一下:用戶輸入「Prefix and Suffix」(前綴和後綴) - 在開始和結尾處有額外的空格。我們不必刪除前綴開頭的額外空間 - 例如: prefix= prefix[:1]

第二個問題:handleTextChanged() - 方法的最後,我們來計算光標的新位置。在目前的情況下,我們使用前綴來獲取字符串的長度。爲什麼不從新的修改過的文本中獲得len,這是前綴和後綴的一部分? 示例:舊字符串是「Prefix and Suffix」,用戶刪除單詞「and」。現在我們的字符串看起來像「Prefix |後綴」畢竟空格被刪除,我們得到了新的修改後的文本:‘前綴後綴’爲什麼我們不計算從修改後的文本的新位置還是我錯過了什麼

編輯3:??

我很抱歉,我還是不明白的情況

第一種情形:當用戶鍵入以下字符串:「A B C |」(|它顯示爲光標)現在,用戶按下空格鍵超過2次,我們得到一個包含「A B C |」的前綴 - 並且沒有後綴。 prexis的ength是6 - 後綴沒有長度,因爲它是空的。整個單詞長度爲6.光標當前位置爲7.

第二種情況:用戶鍵入「A B D E F |」。而現在他意識到一封信失蹤了:C。他在BD之間移動光標,並在C之間移動光標,然後他將要按空格鍵2次。現在我們有包含「A B C」的前綴和內容爲「D E F」的後綴。前綴長度爲6,後綴爲5,整個單詞的長度爲11,此時光標的當前位置爲7.在這種情況下,取前綴長度並設置光標位置,右側?

回答

2

如果你真的想要防止多個空格,過濾按鍵是不夠的。

例如,用戶可以簡單地拖放多個空格;或者使用鼠標,內置的上下文菜單或標準鍵盤快捷方式粘貼它們。

這也很容易打破你的空間鍵計數方法:例如,只需鍵入A B C然後移回兩個地方並刪除B

更爲健壯的方法是連接textChanged信號並使用正則表達式檢查是否有多個空格。如果有,請使用相同的正則表達式替換它們,然後將光標恢復到原始位置。

這裏有一個演示:

import sys, re 
from PyQt4 import QtCore, QtGui 

class Window(QtGui.QWidget): 
    def __init__(self): 
     super(Window, self).__init__() 
     self.edit = QtGui.QLineEdit(self) 
     self.edit.textChanged.connect(self.handleTextChanged) 
     layout = QtGui.QVBoxLayout(self) 
     layout.addWidget(self.edit) 
     self.regexp = re.compile(r'\s\s+') 

    def handleTextChanged(self, text): 
     if self.regexp.search(text): 
      text = unicode(text) 
      # do replacements before and after cursor pos 
      pos = self.edit.cursorPosition() 
      prefix = self.regexp.sub(' ', text[:pos]) 
      suffix = self.regexp.sub(' ', text[pos:]) 
      # cursor might be between spaces 
      if prefix.endswith(' ') and suffix.startswith(' '): 
       suffix = suffix[1:] 
      self.edit.setText(prefix + suffix) 
      self.edit.setCursorPosition(len(prefix)) 

if __name__ == '__main__': 

    app = QtGui.QApplication(sys.argv) 
    window = Window() 
    window.setGeometry(500, 150, 300, 100) 
    window.show() 
    sys.exit(app.exec_()) 
+0

你的演示是非常有用和有益的。我必須要管理員我是Python的初學者。這就是我分析代碼的原因。我想了解一切。我編輯了我的第一個問題。我將我的想法和問題作爲評論寫入代碼。我試圖擺脫你。在這個評論中你會看到我的理解問題,你也會看到我是否正確理解你。 – Sophus

+0

@Sophus。我在你的新代碼中添加了一些註釋(它們都以'#@'開頭)。 – ekhumoro

+0

謝謝。還有另一個理解問題。我在「編輯2:」 – Sophus