占位符文本未显示(pyside/pyqt) [英] Placeholder text not showing (pyside/pyqt)

查看:53
本文介绍了占位符文本未显示(pyside/pyqt)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

学习 PySide,我正在调整文本编辑小部件 (QLineEdit) 并尝试使用 setPlaceHolderText 设置占位符文本,如下面的代码片段(我从 main 调用).不幸的是,它没有按我预期的那样工作.代码运行了,但是文本框是空白的,不显示占位符文本.我在 Windows 7,Python 2.7(在 iPython 中工作).

Learning PySide, I'm tweaking a text edit widget (QLineEdit) and trying to set the placeholder text using setPlaceHolderText as in the code snippet below (which I invoke from main). Unfortunately, it is not working as I expected. The code runs, but the text box is blank, does not show the placeholder text. I am in Windows 7, Python 2.7 (working in iPython).

class MyTextEdit(QtGui.QWidget):
    def __init__(self):
        QtGui.QWidget.__init__(self)
        self.textEditor=QtGui.QLineEdit(self) 
        self.textEditor.move(50,15)
        self.textEditor.setPlaceholderText("Don't mind me.") 
        self.setGeometry(100, 100, 200, 50)
        self.show()        

有人明白我做错了什么吗?我正在关注以下网站的示例:

Anyone understand what I'm doing wrong? I'm following examples from the following sites:

http://nullege.com/codes/search/PyQt4.QtGui.QLineEdit.setPlaceholderText

http://www.pythoncentral.io/pyside-pyqt-tutorial-interactive-widgets-and-layout-containers/

不要看到我在做什么不同.

And don't see what I'm doing differently.

推荐答案

由于您的小部件仅包含一个组件(QLineEdit),因此该组件最初将始终抓住焦点.占位符文本仅在编辑为空时显示并且没有焦点*.

As your widget only contains only one component (the QLineEdit), that component will always grab the focus initially. The placeholder text is only shown if the edit is empty and does not have the focus*.

一个简单的解决方案是在显示您的小部件之前聚焦不同的组件,例如通过在 self.show().
之前插入 self.setFocus()缺点是这种方式用户必须点击进入文本字段或按 Tab 才能写入字段.为避免这种情况,您可以拦截小部件上的 keyPress 事件.

A simple solution would be to focus a different component befor showing your widget, e.g. by inserting self.setFocus() before self.show().
The downside is that this way the user has to click into the text field or press Tab before being able to write into the field. To avoid that, you can intercept the keyPress event on the widget.

示例:

class MyTextEdit(QtGui.QWidget):
    '''Some positioning'''
    def __init__(self):
        QtGui.QWidget.__init__(self)
        self.textEditor=QtGui.QLineEdit(self) 
        self.textEditor.move(50,15)
        self.textEditor.setPlaceholderText("Hi I'm de fault.") 
        self.setGeometry(100, 100, 200, 50)
        self.setFocus()
        self.show()

    def keyPressEvent(self, evt):
        self.textEditor.setFocus()
        self.textEditor.keyPressEvent(evt)

*注意:这在 Qt5 中发生了变化,其中起搏器文本位于只要行编辑为空就显示.不幸的是,PySide 不支持 Qt5(目前),所以你必须使用 PyQt5.

*Note: This has changed in Qt5 where the paceholder text is shown as long as the line edit is empty. Unfortunately PySide doesn't support Qt5 (yet), so you'd have to use PyQt5.

这篇关于占位符文本未显示(pyside/pyqt)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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