[英]How to set the text in the QComboBox to align to the center without making it editable in PyQt
[英]Center non-editable QComboBox Text with PyQt
是否可以更改不可编辑的 QComboBox 的文本对齐方式? 这个答案通过使 QComboBox 可编辑来实现这一点
但是,我不希望这样,因为通过这种更改,触发列表的 ComboBox 的可点击部分现在只是右侧的箭头,而在整个区域可点击并触发下拉菜单之前。
链接问题How to center text in QComboBox? 中已经部分给出了答案。 剩下的就是使只读对象可点击。 这可以按照此处的建议进行。 ...给你以下代码:
from PyQt4 import QtGui, QtCore
class Window(QtGui.QWidget):
def __init__(self):
QtGui.QWidget.__init__(self)
layout = QtGui.QVBoxLayout(self)
self.combo = QtGui.QComboBox()
self.combo.setEditable(True)
self.ledit = self.combo.lineEdit()
self.ledit.setAlignment(QtCore.Qt.AlignCenter)
# as suggested in the comment to
# https://stackoverflow.com/questions/23770287/how-to-center-text-in-qcombobox
self.ledit.setReadOnly(True) #
self.combo.addItems('One Two Three Four Five'.split())
layout.addWidget(self.combo)
self.clickable(self.combo).connect(self.combo.showPopup)
self.clickable(self.ledit).connect(self.combo.showPopup)
def clickable(self,widget):
""" class taken from
https://wiki.python.org/moin/PyQt/Making%20non-clickable%20widgets%20clickable """
class Filter(QtCore.QObject):
clicked = QtCore.pyqtSignal()
def eventFilter(self, obj, event):
if obj == widget:
if event.type() == QtCore.QEvent.MouseButtonRelease:
if obj.rect().contains(event.pos()):
self.clicked.emit()
# The developer can opt for .emit(obj) to get the object within the slot.
return True
return False
filter = Filter(widget)
widget.installEventFilter(filter)
return filter.clicked
if __name__ == '__main__':
import sys
app = QtGui.QApplication(sys.argv)
window = Window()
window.show()
sys.exit(app.exec_())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.