Reputation: 304
I wrote a small example in pyqt. It paint some text first and add three buttons below. However there is some space under the buttons. How to remove those space?
I tried addStrech(1)
, but then the text is gone.
Here is my code:
import sys
from PyQt4 import QtGui, QtCore
class CardWidget(QtGui.QWidget):
def __init__(self):
super(CardWidget, self).__init__()
self.initUI()
def initUI(self):
lButton = QtGui.QPushButton("left")
mButton = QtGui.QPushButton("middle")
rButton = QtGui.QPushButton("right")
sometext = DrawText()
hbox = QtGui.QHBoxLayout()
hbox.addWidget(lButton)
hbox.addStretch(1)
hbox.addWidget(mButton)
hbox.addStretch(1)
hbox.addWidget(rButton)
WButton = QtGui.QWidget()
WButton.setLayout(hbox)
vbox = QtGui.QVBoxLayout()
vbox.addWidget(sometext)
vbox.addStretch(1)
vbox.addWidget(WButton)
self.setLayout(vbox)
self.setGeometry(300, 300, 480, 370)
self.setWindowTitle('Flashcards')
self.show()
class DrawText(QtGui.QWidget):
def __init__(self):
super(DrawText, self).__init__()
self.initUI()
def initUI(self):
self.text = 'some text'
self.setGeometry(0, 0, 200, 400)
#self.setWindowTitle('Draw text')
self.show()
def paintEvent(self, event):
qp = QtGui.QPainter()
qp.begin(self)
self.drawText(event, qp)
qp.end()
def drawText(self, event, qp):
qp.setPen(QtGui.QColor(168, 34, 3))
qp.setFont(QtGui.QFont('Decorative', 10))
qp.drawText(event.rect(), QtCore.Qt.AlignCenter, self.text)
def main():
app = QtGui.QApplication(sys.argv)
ex = CardWidget()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
Upvotes: 0
Views: 1749
Reputation: 3661
I've used setFixedSize(int,int)
in your main window to avoid addStretch(1)
, like this:
def initUI(self):
lButton = QtGui.QPushButton("left")
mButton = QtGui.QPushButton("middle")
rButton = QtGui.QPushButton("right")
sometext = DrawText()
hbox = QtGui.QHBoxLayout()
hbox.addWidget(lButton)
hbox.addWidget(mButton)
hbox.addWidget(rButton)
WButton = QtGui.QWidget()
WButton.setLayout(hbox)
vbox = QtGui.QVBoxLayout()
vbox.addWidget(sometext)
vbox.addWidget(WButton)
self.setLayout(vbox)
self.setGeometry(300, 300, 0, 0)
w = WButton.sizeHint().width()+10
h = WButton.sizeHint().height()+sometext.sizeHint().height()+40
self.setFixedSize(w, h)
self.setWindowTitle('Flashcards')
self.show()
Is that more like how you want it to be? You can also set only height to be fixed, that way there will not be extra space up and down.
Upvotes: 1