python - 使用 PyQt 居中不可编辑的 QComboBox 文本

标签 python css pyqt

是否可以更改不可编辑的 QComboBox 的文本对齐方式?这个答案通过使 QComboBox 可编辑来实现这一点

How to center text in QComboBox?

但是,我不希望这样,因为有了这个更改,ComboBox 中触发列表的可点击部分现在只是右侧的箭头,而在整个区域可点击并触发下拉菜单之前。

最佳答案

部分答案已在链接问题 How to center text in QComboBox? 中给出 剩下的就是使只读对象可单击。这可以按照建议完成 here . ...为您提供以下代码:

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_())

关于python - 使用 PyQt 居中不可编辑的 QComboBox 文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39727416/

相关文章:

python - 属性错误 : 'FeatureChartParser' object has no attribute 'nbest_parse'

python - 使用动态列表中的元素填充 QListWidget

qt - QPushbutton 如何删除 setDefault(True) 创建的颜色

python - 将子流程作为字符串重定向到变量

python selenium 保存的图像为空

html - CSS:向左移动按钮

jQuery 表单对齐插件?

html - 没有出现 CSS 渐变

python - QWebEngineView 中的 Qt 事件传播

python - 从另一个文件导入变量?