Search code examples
pythonpyqt4

How to add border around QWidget?


I am using PyQT4 to create a sample application for a prospective client. I am looking for some way to put a border around a specific widget. Please give me some pointers to look for.

updated :

class CentralWidget(QtGui.QWidget):

    def __init__(self, mainWindow):
        super(CentralWidget, self).__init__()

        self.create(mainWindow)

Above code defines the widget.


Solution

  • According to the stylesheet documentation, QWidget does not support the border property (but it seems to have changed since this answer was originally published, in 2011).

    If your widget is a container of other widgets, then you should use QFrame, as it will allow you to call setFrameStyle and setLineWidth. It is preferable over calling setStyleSheet, since style-sheet will make all child widgets inherit the border property.

    Here it is a complete example:

    from PyQt4 import QtGui,QtCore
    
    class CentralWidget(QtGui.QFrame):
    
        def __init__(self, *args):
            super(CentralWidget, self).__init__(*args)
            # use for a non-contaner widget
            self.setStyleSheet("background-color: rgb(255,0,0); margin:5px; border:1px solid rgb(0, 255, 0); ")
            # use for a container widget
            self.setFrameStyle(QFrame.StyledPanel | QFrame.Plain)
            self.setLineWidth(1)
            
    if __name__ == '__main__':
        import sys
        app = QtGui.QApplication(sys.argv)
        mw = QtGui.QMainWindow()
        w = CentralWidget(mw)
        mw.setCentralWidget(w)
        mw.show()
        w.show()
        app.exec_()