我一直在研究PyQt5,并且recenlty决定为一个简单的聊天客户端制作一个gui。这是我的模型:
我使用了QGridLayout,这就是我得到的:
如何减小底部QTextEdit的大小,因此它有2-3个可用行,并使QPushButton更大?
我的节目:
import sys
from PyQt5.QtWidgets import (QMainWindow, QAction, QApplication, QDesktopWidget,
QDialog, QTextEdit, QGridLayout, QPushButton, QWidget)
from PyQt5.QtGui import QIcon
class Chat(QMainWindow):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.populateUI()
self.resize(400, 400)
self.center()
self.setWindowTitle('Simple Chat')
self.show()
def center(self):
qr = self.frameGeometry()
cp = QDesktopWidget().availableGeometry().center()
qr.moveCenter(cp)
self.move(qr.topLeft())
def populateUI(self):
self.createMenu()
self.statusBar()
centralWidget = CentralWidget()
self.setCentralWidget(centralWidget)
def createMenu(self):
menuBar = self.menuBar()
fileMenu = menuBar.addMenu('&File')
fileMenu.addAction(self.createExitAction())
helpMenu = menuBar.addMenu('&Help')
helpMenu.addAction(self.createAboutAction())
def createExitAction(self):
exitAction = QAction(QIcon('exit.png'), '&Exit', self)
exitAction.setShortcut('Ctrl+Q')
exitAction.setStatusTip('Exit application')
exitAction.triggered.connect(self.close)
return exitAction
def createAboutAction(self):
aboutAction = QAction(QIcon('info.png'), '&About', self)
aboutAction.setShortcut('Ctrl+H')
aboutAction.setStatusTip('Information about the program')
aboutAction.triggered.connect(self.createAboutDialog)
return aboutAction
def createAboutDialog(self):
dialog = QDialog(self)
dialog.setWindowTitle('About')
dialog.setWindowIcon(QIcon('info.png'))
dialog.resize(200, 200)
dialog.exec_()
class CentralWidget(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
ribbon = QTextEdit()
chat = QTextEdit()
sendBtn = QPushButton('Send')
grid = QGridLayout()
grid.setSpacing(3)
grid.addWidget(ribbon, 0, 0, 1, 3)
grid.addWidget(chat, 1, 0, 1, 1)
grid.addWidget(sendBtn, 1, 2)
self.setLayout(grid)
if __name__ == '__main__':
app = QApplication(sys.argv)
chat = Chat()
sys.exit(app.exec_())
答案 0 :(得分:1)
我猜您正在关注setFixedSize(QSize size)的QWidget。
答案 1 :(得分:1)
首先需要根据要显示的行数为底部文本编辑设置固定高度。这还需要考虑框架和文档边距:
def initUI(self):
...
chat.setFixedHeight(
(chat.fontMetrics().lineSpacing() * 3) +
(chat.document().documentMargin() * 2) +
(chat.frameWidth() * 2) - 1
)
然后,您需要更改按钮的大小策略,使其垂直展开:
policy = sendBtn.sizePolicy()
policy.setVerticalPolicy(QSizePolicy.MinimumExpanding)
sendBtn.setSizePolicy(policy)
最后,您需要在第一行和第一列设置拉伸因子,以便文本编辑占用所有可用空间:
grid.setRowStretch(0, 1)
grid.setColumnStretch(0, 1)