![](/img/trans.png)
[英]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.