我必须创建一个QPushButton
其中包含一个图标和 2 行文本。
理想情况下,我应该能够将图标放在左侧(在一个设计上)或放在文本上方的中心(对于另一个 View 中的另一个设计)。
我需要能够单独设置两行文本(甚至具有不同的文本大小)。不是文本换行。
我要对 QPushButton
进行子类化,设置网格布局,并添加图标和2个QLabel。添加setText2()
和text2()
。看起来很简单。
我见过有人建议“只是子类化 xx 控件并添加您自己的布局”,但从未提出过实际的不间断示例。
我的问题:
我必须做什么才能利用 QPushButton
的所有内置属性和事件?我必须做什么才能确保我有正确的调整大小事件,并且为第一行文本添加的图标和标签是 QPushButton
的实际图标和文本以便正确应用它们?
我一直在搜索,但找不到 QPushButton 的绘图元素(QIcon 和文本的容器) - 如果至少我能找到这些元素,这会对我有所帮助,这样我就可以使用它们制作自己的布局。
最佳答案
在子类化之前,我会尝试向 QpushButton
添加布局,并将所需的小部件添加到布局中。为了将事情保持在一起,我宁愿子类化 QWidget
并拥有这样的类:
class CustomButton : public QWidget
{
public:
explicit CustomButton(QWidget * parent);
private:
QPushButton button;
QLabel * icon;
QLabel * line1;
QLabel * line2;
};
只需添加公共(public)方法来设置图标和文本行:
public:
void setTextLines(QString & l1, QString & l2)
{
line1->setText(l1);
line2->setText(l2);
}
void setIcon(QPixmap & pixmap)
{
icon->setPixmap(pixmap);
}
和自定义信号:
signals:
void clicked();
这是一个可能的构造函数,其中实例化小部件并将信号直接连接到按钮信号:
CustomButton::CustomButton(QWidget *parent)
{
button = new QPushButton();
icon = new QLabel(); //use a label to host the icon
line1 = new QLabel();
line2 = new QLabel();
connect(button, SIGNAL(clicked(bool)), this, SIGNAL(clicked()));
QHBoxLayout * hl = new QHBoxLayout();
hl->addWidget(icon);
QVBoxLayout * vl = new QVBoxLayout();
vl->addWidget(line1);
vl->addWidget(line2);
hl->addLayout(vl);
button->setLayout(hl);
QGridLayout * gl = new QGridLayout();
gl->addWidget(button);
setLayout(gl);
}
可以通过专门的方法移动用于排列小部件的代码。
为什么不子类化QPushButton
或QAbstractButton
,这似乎是合乎逻辑的选择?最实际的原因是:像 setText
和 setIcon
这样的方法在此类中不再具有任何意义(甚至是危险的)。通过安全代理公开标签和按钮方法(和信号),并且仅公开所需的方法,这是更好的方法。
关于c++ - 创建一个 2 行(不换行)的 QPushButton,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49452739/