在组合框中的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
(QtWebkit)的QWebViews
?Qt-BUG(建议): https://bugreports.qt.io/browse/QTBUG-35771
最佳答案
我使用 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感谢您的评论,我找到了解决方案
关于c++ - "QComboBox Pop-up"扩展和QtWebkit,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/20554940/