简体   繁体   中英

Center non-editable QComboBox Text with PyQt

Is it possible to change the text alignment of a QComboBox that is not not editable? This answer achieves this by making the QComboBox editable

How to center text in QComboBox?

However, I don't want that because with that change, the clickable part of the ComboBox to trigger the list is now only the arrow on the right, whereas before the entire area was clickable and triggers the drop down menu.

The answer is partly already given in the linked question How to center text in QComboBox? What remains is to make the read-only object clickable. This can be done as suggested here . ...giving you the following code:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM