eri*_*ric 6 python user-interface qt pyqt pyside
学习PySide,我正在调整文本编辑小部件(QLineEdit)并尝试使用setPlaceHolderText设置占位符文本,如下面的代码片段(我从中调用main).不幸的是,它没有像我预期的那样工作.代码运行,但文本框为空,不显示占位符文本.我在Windows 7,Python 2.7(在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()
Run Code Online (Sandbox Code Playgroud)
任何人都明白我做错了什么?我正在关注以下网站的示例:
http://nullege.com/codes/search/PyQt4.QtGui.QLineEdit.setPlaceholderText
http://www.pythoncentral.io/pyside-pyqt-tutorial-interactive-widgets-and-layout-containers/
而且看不出我在做什么不同.
mat*_*ata 12
由于您的窗口小部件仅包含一个组件(QLineEdit),该组件将始终抓住焦点.仅当编辑为空且没有焦点*时,才会显示占位符文本.
一个简单的解决方案是将一个不同的组件集中在一起,以显示您的小部件,例如通过self.setFocus()之前插入self.show().
缺点是这样用户必须点击文本字段或按下Tab才能写入字段.为避免这种情况,您可以拦截keyPress窗口小部件上的事件.
例:
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)
Run Code Online (Sandbox Code Playgroud)
*注意:这在Qt5中已经改变,只要行编辑为空,就会显示提示者文本.不幸的是PySide不支持Qt5,所以你必须使用PyQt5.