【问题标题】:How to customize a QPushbutton in Qt code如何在 Qt 代码中自定义 QPushbutton
【发布时间】:2017-01-29 09:26:38
【问题描述】:

假设我在“C++ 代码”中创建了一个名为 my_button 的按钮:

QPushButton* my_button = new QPushButton (tr("OK"));

现在我想按如下方式操作这个按钮:

  1. 将字体更改为斜体粗体(例如,OKOK
  2. 为其设置红色或蓝色
  3. 使字体变大/变小
  4. 更改其大小(高度和宽度)
  5. 改变它的位置(向右/向左/向上/向下)

我搜索了网络糊状物,但找不到完成所有工作的方法。 如果你能告诉我如何做这些,我会很感谢你。

【问题讨论】:

标签: c++ qt qt5


【解决方案1】:

要更改按钮的特性,您可以使用fontstylesheet,移动move() 函数,并使用resize() 函数调整大小。 您无需搜索整个网络,最好的来源始终是documentation

QFont font = {your Button}->font();
font.setBold(true); //set style bold if is true
font.setItalic(true); //set style italic if is true
font.setPixelSize(20); // Sets the font size to pixelSize pixels.
{your Button}->setFont(font);
//change color
QString Buttonstyle = "QPushButton {background-color: #0000FF,
                       color: red;}");

{your Button}->setStyleSheet(Buttonstyle);
{your Button}->move({posx}, {posy});
{your Button}->resize({width}, {height});

【讨论】:

    【解决方案2】:
    QString ButtonStye = "{font: 75 12pt \"Tahoma\"";
            "color: rgb(255, 0, 0);"
            "width : 50px;"
            "height: 25px;"
        "}";
    
    my_button->setStyleSheet(ButtonStye);
    

    您可以更改宽度、高度、颜色 abd 字体的磅值和系列。 Qt 有限支持 CSS。 Look At Qt Official Page's How CSS Code implement a specific Widget.

    如果你把你的小部件(QPushButton)放在正确的位置,你可以使用 QHBoxLayout 或 QVBoxLayout 来定位。

    【讨论】:

    • 所以你说定位小部件(这里是 QPushButton)的唯一方法是使用 QH/VBoxLayout
    • 你问在 5 处改变它的位置。你的意思是什么?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-15
    • 2012-06-03
    • 2022-01-13
    • 2019-06-26
    • 1970-01-01
    相关资源
    最近更新 更多