我想使用Qt4.7在QTableWidget中启用mouseTracking。通常这应该是直接使用setMouseTracking(true)。这适用于其他小部件,但QTableWidget可以抵御它。为了激活mouseTracking,我有什么特别的处理方法吗?
虽然我实际上正在做更复杂的事情,但我可以通过在mouseMoveEvent中打印出QMouseEvent.x()而无法启用它。 谢谢到目前为止:)
以下是我的尝试:
QGridLayout * layout = new QGridLayout(this);
SCTableWidget * aTable = new SCTableWidget(tableRows, tableCols, this);
QTableWidgetItem * newItem;
for(int i = 0; i<(3); i++) {
for(int j = 0; j<(17); j++) {
newItem = new QTableWidgetItem(QString::number(tableData[i][j]));
aTable->setItem(i,j, newItem);
}
}
// First try
aTable->setMouseTracking(true);
//Second try. Main Window further down.
MainWindow::instance->enableMouseTracking(aTable->children());
MainWindow::instance->enableMouseTracking(aTable->viewport()->children());
// Third try
aTable->viewport()->setMouseTracking(true);
layout->addWidget(aTable, 0, 0, 1, 2);
第二次尝试包含一个在MainWindow中实现的方法,如下所示:
void
MainWindow::enableMouseTracking(const QObjectList & pChildren)
{
foreach(QObject * obj, pChildren)
{
QWidget * w = qobject_cast<QWidget *>(obj);
if(w)
{
w->setMouseTracking(true);
enableMouseTracking(w->children());
}
}
}
答案 0 :(得分:3)
开启QTableWidget-&gt; viewport()的鼠标跟踪通常有效。您是否还在为QTableWidget-&gt; viewport()小部件捕捉鼠标事件?请检查下面的示例是否适合您:
test.h:
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
bool eventFilter(QObject *obj, QEvent *event);
private:
Ui::MainWindow *ui;
QTableWidget *table;
};
TEST.CPP:
MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
table = new QTableWidget(5, 10, this);
table->setGeometry(10, 20, 300, 200);
for (int row=0; row<5; ++row)
for (int column=0; column<10; ++column)
table->setItem(row, column, new QTableWidgetItem(tr("%1").arg((row+1)*(column+1))));
table->setMouseTracking(true);
table->viewport()->setMouseTracking(true);
table->installEventFilter(this);
table->viewport()->installEventFilter(this);
}
MainWindow::~MainWindow()
{
delete ui;
}
bool MainWindow::eventFilter(QObject *obj, QEvent *event)
{
if (obj == table)
{
if (event->type() == QEvent::MouseButtonPress)
qDebug() << "table mouse press event";
else if (event->type() == QEvent::MouseMove)
qDebug() << "table mouse moveevent";
}
else if (obj == table->viewport())
{
if (event->type() == QEvent::MouseButtonPress)
qDebug() << "table->viewport mouse press event";
else if (event->type() == QEvent::MouseMove)
qDebug() << "table->viewport mouse moveevent";
}
return QMainWindow::eventFilter(obj, event);
}
希望这有帮助,尊重
答案 1 :(得分:2)
默认情况下,鼠标事件被禁用,因为QAbstractItemView
实现了mousePressEvent
,mouseReleaseEvent
等功能,而QTableWidget
根本没有实现它们,这意味着QAbstractItemView
中的函数阻止了鼠标消息。
因此解决这个问题的一个非常简单的方法是继承QTableWidget
类,并自己提供鼠标信号,它应该非常简单,只需尝试一下!
答案 2 :(得分:0)
这对我有用:
aTable->setMouseTracking(true);
aTable->viewport()->setMouseTracking(true);