在组合框的Firefox / Chrome / InternetExplorer / Safari / Opera弹出窗口中展开内容,请参阅Firefox图片:
QComboBox
弹出窗口不会扩展内容。 弹出窗口受QComboBox
大小的限制,请参阅 QWebView 图片:
所以我实现了 QComboBox :: showPopup :
void newQComboBox::showPopup() {
int width = this->width();
this->view()->setTextElideMode( Qt::ElideNone );
const int iconSize = this->iconSize().width();
const QFontMetrics fontMetrics = this->fontMetrics();
const int j = this->count();
for( int i=0; i < j; ++i ) {
const int textWidth = fontMetrics.width( this->itemText(i) + "WWW" );
if (this->itemIcon(i).isNull()) {
width = qMax(width, textWidth);
} else {
width = qMax(width, textWidth + iconSize);
}
}
QStyleOptionComboBox opt;
this->initStyleOption(&opt);
QSize size(width, 0);
size = this->style()->sizeFromContents(QStyle::CT_ComboBox, &opt, size, this);
this->view()->setFixedWidth( width );
QComboBox::showPopup();
}
有没有办法修改(重新实现)QComboBox::showPopup
QWebViews
(QtWebkit)?
Qt-BUG(建议): https://bugreports.qt.io/browse/QTBUG-35771
答案 0 :(得分:6)
我使用QProxyStyle
类解决了,例如:
#include <QProxyStyle>
#include <QAbstractItemView>
#include <QComboBox>
class myProxyStyle : public QProxyStyle
{
public:
int styleHint(StyleHint hint, const QStyleOption *option, const QWidget *widget, QStyleHintReturn *returnData) const
{
if(hint == QStyle::SH_ComboBox_Popup) {
const QComboBox *combo = (QComboBox *) widget;//cast to QComboBox
const QObjectList a = combo->children();
const int j = a.count();
QAbstractItemView *view = 0;
QString className = "";
bool hasView = false;
/*
at this point I have not used combo->view() because he "crash" the application without explanation
so I had to make a loop to find the "view"
*/
for (int i = 0; i < j; ++i) {
const QObjectList b = a.at(i)->children();
const int y = b.count();
for (int x = 0; x < y; ++x) {
className = b.at(x)->metaObject()->className();
if (className == "QComboBoxListView") {
view = (QAbstractItemView *) b.at(x);
hasView = true;
break;
}
}
if (hasView) {
break;
}
}
if (hasView) {
const int iconSize = combo->iconSize().width();
const QFontMetrics fontMetrics1 = view->fontMetrics();
const QFontMetrics fontMetrics2 = combo->fontMetrics();
const int j = combo->count();
int width = combo->width(); //default width
for (int i = 0; i < j; ++i) {
const int textWidth = qMax(
fontMetrics1.width(combo->itemText(i) + "WW"),
fontMetrics2.width(combo->itemText(i) + "WW")
);
if(combo->itemIcon(i).isNull()) {
width = qMax(width, textWidth);
} else {
width = qMax(width, textWidth + iconSize);
}
}
view->setFixedWidth(width);
}
}
return QProxyStyle::styleHint(hint, option, widget, returnData);
}
};
使用方法:
您必须申请QApplication
(通常是文件main.cpp
):
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
a.setStyle(new myProxyStyle);//set ProxyStyle
return a.exec();
}
@peppe感谢您的评论我得到了解决方案
答案 1 :(得分:-2)
请尝试使用setMinimumWidth函数并传递您计算的最大宽度。它应该工作 的 ui.comboBox-&gt;查看() - &GT; setMinimumWidth(宽度); 强> 有关详情,请浏览https://qt-project.org/forums/viewthread/26388链接