Nar*_*rek 7 c++ formatting qt button
我有一个QPushButton,我有一个文本和图标.我想让按钮上的文字变为粗体和红色.看着其他论坛,谷歌搜索,失去了我的希望.如果按钮有一个图标,那么似乎没有办法做到这一点(当然,如果你没有创建一个新的图标,那就是文字+前图标).这是唯一的方法吗?谁有更好的主意?
Har*_*ich 18
你真的不需要子类来改变你的按钮的格式,而是使用样式表,例如
QPushButton {
font-size: 18pt;
font-weight: bold;
color: #ff0000;
}
Run Code Online (Sandbox Code Playgroud)
将此应用于要更改的按钮将使按钮文本为18pt,粗体和红色.你可以通过申请widget->setStyleSheet()
将此应用于上面层次结构中的窗口小部件将为下面的所有按钮设置样式,QT样式表机制非常灵活且记录良好.
您也可以在设计器中设置样式表,这将为您正在编辑的窗口小部件设置样式
你创建"QPushbutton"的子类,然后覆盖绘制事件,在那里你根据自己的意愿修改文本.
这里是,
class button : public QPushButton
{
Q_OBJECT
public:
button(QWidget *parent = 0)
{
}
~button()
{
}
void paintEvent(QPaintEvent *p2)
{
QPushButton::paintEvent(p2);
QPainter paint(this);
paint.save();
QFont sub(QApplication::font());
sub.setPointSize(sub.pointSize() + 7);
paint.setFont(sub);
paint.drawText(QPoint(300,300),"Hi");
paint.restore();
}
};
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
button b1;
b1.showMaximized();
return a.exec();
}
Run Code Online (Sandbox Code Playgroud)
笔记:
My answer is inspired by the idea from @\xd0\x9f\xd0\xb5\xd1\x82\xd1\x8a\xd1\x80 \xd0\x9f\xd0\xb5\xd1\x82\xd1\x80\xd0\xbe\xd0\xb2 and the comment from @mjwach.
你可以子类化QPushButton and give it two private fields:
self.__lbl: AQLabel() instance to hold the rich text. Its background is made transparent and it doesn\'t catch mouse events.self.__lyt: AQHBoxLayout() to hold the label. The layout margins are set to zero, such that the label\'s borders touch the button\'s borders. In other words: we ensure that the label has the exact same size as the button, and is positioned right on top of it.最后你必须重写setText() method, such that the text ends up in the label instead of the button.
class RichTextPushButton(QPushButton):\n def __init__(self, parent=None, text=None):\n if parent is not None:\n super().__init__(parent)\n else:\n super().__init__()\n self.__lbl = QLabel(self)\n if text is not None:\n self.__lbl.setText(text)\n self.__lyt = QHBoxLayout()\n self.__lyt.setContentsMargins(0, 0, 0, 0)\n self.__lyt.setSpacing(0)\n self.setLayout(self.__lyt)\n self.__lbl.setAttribute(Qt.WA_TranslucentBackground)\n self.__lbl.setAttribute(Qt.WA_TransparentForMouseEvents)\n self.__lbl.setSizePolicy(\n QSizePolicy.Expanding,\n QSizePolicy.Expanding,\n )\n self.__lbl.setTextFormat(Qt.RichText)\n self.__lyt.addWidget(self.__lbl)\n return\n\n def setText(self, text):\n self.__lbl.setText(text)\n self.updateGeometry()\n return\n\n def sizeHint(self):\n s = QPushButton.sizeHint(self)\n w = self.__lbl.sizeHint()\n s.setWidth(w.width())\n s.setHeight(w.height())\n return s\nRun Code Online (Sandbox Code Playgroud)\n