标题:如何让combox的内容居中显示
作者:床前明月光
日期:2021-09-29 14:33
内容:
如何让combox的内容居中显示,尝试了加入Qlineedit,设置居中后,设置不了只读模式。不知道还有什么方法能让combox的内容居中显示
#1 [272064949 09-30 14:41]
class MyComboBox : public QComboBox
{
public:
MyComboBox(QWidget *parent = nullptr):QComboBox(parent)
{
}
void paintEvent(QPaintEvent *)
{
QPainter p(this);
p.drawRect(this->rect().adjusted(0,0,-1,-1));
p.drawText(this->rect(), Qt::AlignCenter, this->currentText());
qDebug()isVisible();
}
};
Widget::Widget(QWidget *parent)
: QWidget(parent)
, ui(new Ui::Widget)
{
ui->setupUi(this);
MyComboBox *cb = new MyComboBox(this);
ui->horizontalLayout_2->addWidget(cb);
for(int i=0; iaddItem("======"+QString::number(i));
}
}
看了一下,用qss确实不好操作,试着继承控件,然后重写绘图函数,自己画试试
#2 回 272064949 的帖子 [床前明月光 10-11 10:19]
272064949:class MyComboBox : public QComboBox
{
public:
MyComboBox(QWidget *parent = nullptr):QComboBox(parent)
{
....... (2021-09-30 14:41)
你好,我按照你的代码,确实可以把自写的combox文字居中了,但是这个combox的样式表确不能用setstylesheet设置了,这是怎么回事呢?麻烦您再看下,感谢感谢
#3 [zy1233 10-11 15:22]
QComboBox.lineEdit()->setAlignment(Qt::AlignCenter);
#4 回 zy1233 的帖子 [床前明月光 10-18 14:55]
zy1233:QComboBox.lineEdit()->setAlignment(Qt::AlignCenter); (2021-10-11 15:22)
这个方法其实不太好,在combox中加入lineedit后,只能点下拉按钮才会显示下拉项,点lineedit不会下拉
#5 [steinlee 10-22 11:23]
QComboBox {
border: 1px solid gray;
border-radius: 3px;
padding: 1px 18px 1px 3px;
min-width: 6em;
}
可以用stylesheet 加padding