• 2026阅读
  • 5回复

[提问]如何让combox的内容居中显示 [复制链接]

上一主题 下一主题
 

只看楼主 倒序阅读 楼主  发表于: 2021-09-29
如何让combox的内容居中显示,尝试了加入Qlineedit,设置居中后,设置不了只读模式。不知道还有什么方法能让combox的内容居中显示
离线272064949

只看该作者 1楼 发表于: 2021-09-30
  1. class MyComboBox : public QComboBox
  2. {
  3. public:
  4.     MyComboBox(QWidget *parent = nullptr):QComboBox(parent)
  5.     {
  6.     }
  7.     void paintEvent(QPaintEvent *)
  8.     {
  9.         QPainter p(this);
  10.         p.drawRect(this->rect().adjusted(0,0,-1,-1));
  11.         p.drawText(this->rect(), Qt::AlignCenter, this->currentText());
  12.         qDebug()<<this->view()->isVisible();
  13.     }
  14. };
  15. Widget::Widget(QWidget *parent)
  16.     : QWidget(parent)
  17.     , ui(new Ui::Widget)
  18. {
  19.     ui->setupUi(this);
  20.     MyComboBox *cb = new MyComboBox(this);
  21.     ui->horizontalLayout_2->addWidget(cb);
  22.     for(int i=0; i<20; i++)
  23.     {
  24.         cb->addItem("======"+QString::number(i));
  25.     }
  26. }



  看了一下,用qss确实不好操作,试着继承控件,然后重写绘图函数,自己画试试

只看该作者 2楼 发表于: 2021-10-11
回 272064949 的帖子
272064949:class MyComboBox : public QComboBox
{
public:
    MyComboBox(QWidget *parent = nullptr):QComboBox(parent)
    {
....... (2021-09-30 14:41) 

你好,我按照你的代码,确实可以把自写的combox文字居中了,但是这个combox的样式表确不能用setstylesheet设置了,这是怎么回事呢?麻烦您再看下,感谢感谢
离线zy1233

只看该作者 3楼 发表于: 2021-10-11
QComboBox.lineEdit()->setAlignment(Qt::AlignCenter);

只看该作者 4楼 发表于: 2021-10-18
回 zy1233 的帖子
zy1233:QComboBox.lineEdit()->setAlignment(Qt::AlignCenter); (2021-10-11 15:22) 

这个方法其实不太好,在combox中加入lineedit后,只能点下拉按钮才会显示下拉项,点lineedit不会下拉
离线steinlee

只看该作者 5楼 发表于: 2021-10-22
QComboBox {
    border: 1px solid gray;
    border-radius: 3px;
    padding: 1px 18px 1px 3px;
    min-width: 6em;
}
可以用stylesheet 加padding
Looking for remote C/C++ and Qt 兼职
快速回复
限100 字节
 
上一个 下一个