Tymofii Koval
Tymofii Koval

Reputation: 183

How to make buttons from scratch in PyQt5?

During making my program I needed to create a widget with QTextEdit and QPushButton on it. I did this but the button looked like 3D object. Before this I supposed the button to be flat.

I was trying to change color of the button but it still has volume.

from PyQt5 import QtWidgets
class Window(QtWidgets.QWidget):
    def __init__(self):
        QtWidgets.QWidget.__init__(self)
        self.resize(300, 200)
        self.setStyleSheet('background-color: white')
        self.setWindowTitle('Test')
        self.button = QtWidgets.QPushButton('Button')
        self.box = QtWidgets.QVBoxLayout()
        self.box.addWidget(self.button)
        self.setLayout(self.box)
if __name__ == '__main__':
    import sys
    app = QtWidgets.QApplication(sys.argv)
    win = Window()
    win.show()
    sys.exit(app.exec_())

How can I deal with it if I want the window to stay white and the button to be flat?

Any help will be appreciated.

Upvotes: 2

Views: 1129

Answers (1)

eyllanesc
eyllanesc

Reputation: 244359

You have to set the flat property of the button to True in addition to removing the border:

from PyQt5 import QtWidgets

qss = """
#Window{ 
    background-color: white 
}
QPushButton[flat="true"]{
    background-color: black;
    border: 0px;
}
"""


class Window(QtWidgets.QWidget):
    def __init__(self, parent=None):
        super(Window, self).__init__(parent)
        self.resize(300, 200)
        self.setObjectName("Window")
        self.setWindowTitle("Test")
        self.button = QtWidgets.QPushButton("Button", flat=True)

        box = QtWidgets.QVBoxLayout(self)
        box.addWidget(self.button)


if __name__ == "__main__":
    import sys

    app = QtWidgets.QApplication(sys.argv)
    app.setStyleSheet(qss)
    win = Window()
    win.show()
    sys.exit(app.exec_())

Upvotes: 2

Related Questions