减小 QPushButton 的文本和边缘之间的距离?
Decreasing distance between text and edge for QPushButton?
我们怎样才能减少QPushButton
中的文本字符串和边缘之间的距离?
对我来说(在 LXDE 上)它现在看起来像这样:
self.on_qpb = QtWidgets.QPushButton(self.tr("On"))
hbox.addWidget(self.on_qpb)
self.on_qpb.setCheckable(True)
self.on_qpb.toggled.connect(self.on_on_toggled)
我们希望这样:
我们使用 setFixedWidth
实现了后者,但在翻译成其他语言时会产生问题
你能推荐什么?感谢您的帮助!
一个可能的解决方案是在 QFontMetrics
的帮助下根据文本设置文本的宽度,或者您可以创建一个 class 来实现具有大小策略和 return 一个适当的 sizeHint()
如下例所示:
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
class PushButton(QPushButton):
def __init__(self, *args, **kwargs):
QPushButton.__init__(self, *args, **kwargs)
self.setSizePolicy(QSizePolicy.Maximum, QSizePolicy.Maximum)
def sizeHint(self):
w = self.fontMetrics().width(" {} ".format(self.text()))
h = QPushButton.sizeHint(self).height()
return QSize(w, h)
class Widget(QWidget):
def __init__(self, *args, **kwargs):
QWidget.__init__(self, *args, **kwargs)
hbox = QHBoxLayout(self)
self.on_qpb = QPushButton(self.tr("On"))
self.on_qpb.setCheckable(True)
self.on_qpb.setFixedWidth(self.on_qpb.fontMetrics().width(" {} ".format(self.on_qpb.text())))
self.off_qpb = PushButton(self.tr("Off"))
self.off_qpb.setCheckable(True)
hbox.addWidget(self.on_qpb)
hbox.addWidget(self.off_qpb)
if __name__ == '__main__':
import sys
app = QApplication(sys.argv)
w = Widget()
w.show()
sys.exit(app.exec_())
我们怎样才能减少QPushButton
中的文本字符串和边缘之间的距离?
对我来说(在 LXDE 上)它现在看起来像这样:
self.on_qpb = QtWidgets.QPushButton(self.tr("On"))
hbox.addWidget(self.on_qpb)
self.on_qpb.setCheckable(True)
self.on_qpb.toggled.connect(self.on_on_toggled)
我们希望这样:
我们使用 setFixedWidth
实现了后者,但在翻译成其他语言时会产生问题
你能推荐什么?感谢您的帮助!
一个可能的解决方案是在 QFontMetrics
的帮助下根据文本设置文本的宽度,或者您可以创建一个 class 来实现具有大小策略和 return 一个适当的 sizeHint()
如下例所示:
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
class PushButton(QPushButton):
def __init__(self, *args, **kwargs):
QPushButton.__init__(self, *args, **kwargs)
self.setSizePolicy(QSizePolicy.Maximum, QSizePolicy.Maximum)
def sizeHint(self):
w = self.fontMetrics().width(" {} ".format(self.text()))
h = QPushButton.sizeHint(self).height()
return QSize(w, h)
class Widget(QWidget):
def __init__(self, *args, **kwargs):
QWidget.__init__(self, *args, **kwargs)
hbox = QHBoxLayout(self)
self.on_qpb = QPushButton(self.tr("On"))
self.on_qpb.setCheckable(True)
self.on_qpb.setFixedWidth(self.on_qpb.fontMetrics().width(" {} ".format(self.on_qpb.text())))
self.off_qpb = PushButton(self.tr("Off"))
self.off_qpb.setCheckable(True)
hbox.addWidget(self.on_qpb)
hbox.addWidget(self.off_qpb)
if __name__ == '__main__':
import sys
app = QApplication(sys.argv)
w = Widget()
w.show()
sys.exit(app.exec_())