点击窗口上的其他位置时如何从QLineEdit中删除焦点 [英] How to remove focus from a QLineEdit when anyplace else on the window is clicked

查看:3347
本文介绍了点击窗口上的其他位置时如何从QLineEdit中删除焦点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理一个自定义的Qt按钮,允许您编辑按钮上的文本,如果您双击它。当双击按钮时,QLineEdit出现在按钮上的文本允许用户编辑按钮上的文本的地方。我的要求是,如果用户点击应用程序窗口中的任何地方,QLineEdit应该消失并取消编辑操作。这在一些情况下起作用。具体来说,如果我点击任何能够输入文本的东西,它就可以工作。窗口的其他部分不能按预期工作。我将点击应用程序窗口的一个空白部分,而QLineEdit保留其重点。如何在这些情况下删除它的焦点?

解决方案

我找到了一个解决方案似乎工作,虽然我如果有任何其他选择仍然开放。我正在使用PyQt4,所以我的例子是在Python:



创建一个QLineEdit的子类,所以我有一个新的类型。我不希望或需要在所有的QLineEdit实例上的这种行为;

  class MyLineEdit(QtGui.QLineEdit):
传递
mousePressEvent()
实现。它获取当前焦点小部件。如果该小部件的类型为 MyLineEdit ,请清除焦点。

  class MyMainWindow(QtGui.QMainWindow):
def ...

def mousePressEvent (self,event):
focused_widget = QtGui.QApplication.focusWidget()
if isinstance(focused_widget,MyLineEdit):
focused_widget.clearFocus()
QtGui.QMainWindow.mousePressEvent self,event)

def ...

我正在寻找,如果用户点击应用程序的窗口上的任何地方,焦点被清除。




编辑:我找到了一个警告。我在主窗口中有一个 QTreeView 。如果用户点击树状视图,则不会从文本编辑字段中移除焦点。


I'm working on a custom Qt button that allows you to edit the text on the button if you double click it. When the button is double clicked, a QLineEdit appears where the text on the button is allowing the user to edit the text on the button. My requirement is that if the user clicks anywhere in the application window, the QLineEdit should disappear and cancel the edit operation. This works in some cases. Specifically, it works if I click on anything that is capable of text entry. Other portions of the window don't work as expected. I'll click on a blank portion of the application window, and the QLineEdit retains its focus. How can I remove its focus in these cases?

解决方案

I've found a solution that seems to work, though I'm still open to other options if there are any. I'm using PyQt4, so my example is in python:

Create a subclass of QLineEdit just so I have a new type. I don't want or need this behavior on all QLineEdit instances; just these specific ones.

class MyLineEdit(QtGui.QLineEdit):
    pass

Now, in my QMainWindow subclass, I override the mousePressEvent() implementation. It gets the currently focused widget. If that widget is of type MyLineEdit, clear the focus.

class MyMainWindow(QtGui.QMainWindow):
    def ...

    def mousePressEvent(self, event):
        focused_widget = QtGui.QApplication.focusWidget()
        if isinstance(focused_widget, MyLineEdit):
            focused_widget.clearFocus()
        QtGui.QMainWindow.mousePressEvent(self, event)

    def ...

This gets me the behavior I'm looking for so that if the user clicks anywhere on the application's window, the focus is cleared.


Edit: I did find one caveat to this. I have a QTreeView in the main window. If the user clicks on the tree view, focus is not removed from the text edit field.

这篇关于点击窗口上的其他位置时如何从QLineEdit中删除焦点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆