I'm having an issue where a custom widget I am making appears just fine when added to a QGridLayout without specifying an alignment, but when I specify an Alignment it disappears.

Here is the custom widget:

class OutlineLabel(QWidget):
    def __init__(self, text, parent=None):
        QWidget.__init__(self, parent)
        self.text = text

    def paintEvent(self, event=None):
        painter = QPainter(self)
        path = QPainterPath()
        pen = QPen();
        font = QFont("Helvetica", 14, 99, False)
        brush = QBrush(QtCore.Qt.white)
        pen.setWidth(1);
        pen.setColor(QtCore.Qt.black);
        painter.setFont(font);
        painter.setPen(pen);
        painter.setBrush(brush)
        path.addText(0, 20, font, self.text); 
        painter.drawPath(path);

Here is an example where it will display just fine:

app = QApplication(sys.argv)
wnd = QWidget()
wnd.resize(400,400)
grid = QGridLayout()
test = OutlineLabel("hello")
grid.addWidget(test, 0, 0)
wnd.setLayout(grid)
wnd.show()
sys.exit(app.exec_())

But if I change it to the following, it no longer shows:

app = QApplication(sys.argv)
wnd = QWidget()
wnd.resize(400,400)
grid = QGridLayout()
test = OutlineLabel("hello")
grid.addWidget(test, 0, 0, QtCore.Qt.AlignHCenter)
wnd.setLayout(grid)
wnd.show()
sys.exit(app.exec_())

Is there some information I need to set in the OutlineLabel class to work correctly with Alignments?

有帮助吗?

解决方案

It could be a problem with size hint (your widget is empty).

If you reimplement the sizeHint() method to return a valid QSize, your widget should appear:

def sizeHint( self ):
    return QSize( 200, 200 )
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top