はんぎょねこの憂鬱

耳から変な汁が出てきた

Widgetを等倍で中央寄せさせておきたい!

QScrollAreaのresizeEventを継承してゴニョゴニョしたら割と簡単にできた

f:id:dungeonneko:20170216171205g:plain

import sys
from PySide import QtCore, QtGui

class AlwaysCenterAlign(QtGui.QScrollArea):
    def __init__(self):
        super().__init__()
        self.setAlignment(QtCore.Qt.AlignCenter)
        self.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
        self.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)

    def resizeEvent(self, event):
        super().resizeEvent(event)
        v = self.verticalScrollBar()
        h = self.horizontalScrollBar()
        v.setValue(v.minimum() + (v.maximum() - v.minimum()) / 2)
        h.setValue(h.minimum() + (h.maximum() - h.minimum()) / 2)

    def wheelEvent(self, _):
        pass

    def keyPressEvent(self, _):
        pass

if __name__ == '__main__':
    a = QtGui.QApplication(sys.argv)
    s = AlwaysCenterAlign()
    l = QtGui.QLabel()
    l.setPixmap(QtGui.QPixmap('lena.jpg'))
    s.setWidget(l)
    s.show()
    sys.exit(a.exec_())